I understand that templates kinda get blamed for binary bloat, I also understand that a template is just a pattern. I dont really understand the nuts and bolts as it where.
Alot of time I see code like the following where it returns a base class pointer.
class GameObject
{
public:
Component* getComponent(std::string key);
};
static_cast<Comp>(obj.getComponent("Comp"));
Rather than making the method a template method.
class GameObject
{
public:
template<typename T>
T* getComponent(std::string key);
};
obj.getComponent<Comp>("Comp");
Is this stylistic or is there a performance loss associated with the templates?
The fact that the method takes the “key” which appears to be really a type (the type of component to return) indicates to me that the type is not really known until runtime. If that’s the case then a compile time mechanism like templates will not do.
The only option is to return a base class pointer. And typically when this pattern is used, only virtual methods are called against the base class–so the actual type of the derived class doesn’t matter (so no static_cast or dynamic_cast is needed).
Edit:
As PhilCK noted in comments, the type is actually known at compile time. If that is the case then dynamic type lookup was never really needed, and simple factory methods could have been used:
So there are 2 choices the way I see it.
1) use simple factory methods in which case templates are not needed at all.
2) use map -> factory method implementation together with dynamic_cast (which seems to defeat the purpose of using dynamic type creation) and is actually unnecessarily complex if dynamic types aren’t needed