Hi everyone,

Wondering if anyone could help with a minor problem...

I have a class that contains a std::map that stores pointers to various objects as a void pointer and a name for the object, so within the class I have a template function where the object type is passed, as well as the object name in order to find it - if found, it will cast the void pointer to the corresponding object pointer type. So the function call looks like

MyClass* new = objectHolder->getObject <MyClass> ("MyClassname");

But is it possible to do it like this

MyClass* new = objectHolder->getObject ("MyClassname", MyClass);


Thanks in advance for any help :)

4 Years
Discussion Span
Last Post by mike_2000_17

I don't see the benefit here, especially given the hoops you'd have to jump through to achieve the desired syntax. Is it possible? Yes. Is it worth it? Only if you can come up with a justification that amounts to more than saving two keystrokes (the angle brackets in this case). Oh, and new isn't a legal variable name. ;)


AH yes just realised what I had typed there lol yeah was just curious as too whether it could be done or not thats all :)


As deceptikon says, it can be done, and probably more easily through function overloading (a free function taking the ObjectHolder and the ClassName and type), because then you can overload based on the class type and change the return type accordingly, which is harder to do as member functions.

However, there really isn't any point to doing this. If you consider this expression:

MyClass* ptr = objectHolder->getObject <MyClass> ("MyClassname");


auto ptr = objectHolder->getObject <MyClass> ("MyClassname");

It is very terse and clear already. You can almost read it from left to right as a normal sentence: "Ask objectHolder to get an object of type MyClass with name "MyClassname"". How clearer do you need it to be? Although you could do it your way, it would be a bit hard (under-the-hood), it would probably not be as nice as you'd like (probably would result in:

auto ptr = getObject(objectHolder, "MyClassname", (MyClass*)(NULL));

, and you would be breaking the conventions of C++, that is, type-parameters are as template arguments and value-parameters are as function parameters, trying to flip that around is useless, unclear, difficult and weird for everybody else.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.