Reputation: 2131
I have the following method declared in the public area of a class like that:
In the header file:
class EntityManager
{
public:
...
template <typename ComponentType>
bool addComponentToEntity(const Entity in_Entity, const shared_ptr<ComponentType> in_ComponentInstance);
...
}
In the source file:
template <typename ComponentType>
bool EntityManager::addComponentToEntity(const Entity in_Entity, const shared_ptr<ComponentType> in_ComponentInstance)
{
...
}
Then I try to use it like this:
Entity l_Entity = 1;
shared_ptr<TestComponent> l_TestComponent(new TestComponent());
EntityManager* l_EntityManager = new EntityManager();
l_EntityManager->addComponentToEntity<TestComponent>(l_Entity, l_TestComponent);
This results in the compiler complaining:
undefined reference to `bool EntityManager::addComponentToEntity<TestComponent>(unsigned long, boost::shared_ptr<TestComponent>)'|
I am aware that this is probably because I am not very experienced in C++ programming, but I can't see a reason why the function is undefined. I ommitted some other code that calls other functions of the EntityManager class and that works perfectly well.
I also tried rewriting the function with regular pointers, references and even passes by value with the same result.
Upvotes: 0
Views: 135
Reputation: 6678
Template methods/functions must be defined in the header itself (unless the method's class itself is defined in a source file). This is also the case for all methods of a template class (even if the methods themselves aren't template methods).
Most people don't even bother defining them below the class definition, they just define them inline inside the class:
class EntityManager
{
public:
...
template <typename ComponentType>
bool addComponentToEntity(const Entity in_Entity, const shared_ptr<ComponentType> in_ComponentInstance)
{
...
}
...
}
Upvotes: 1