I keep receiving linker errors when I do this:
//function declaration
template<typename T>
T * EntityManager::GetComponent(EID _entity, CType _type)
//Main.cpp
Position * pos = GetComponent<Position>(eid, POSITION);
Error LNK2019 unresolved external symbol "public: struct Position * __thiscall EntityManager::GetComponent(unsigned int,enum CType)" (??$GetComponent@UPosition@@@EntityManager@@QAEPAUPosition@@IW4CType@@@Z) referenced in function _main
I believe the error resides in "struct Position * GetComponent(...)" I don't want it to return a "struct Position pointer" I want it to return a "Position pointer!" I've tried various template prefaces such as "class" and "struct"
I would like for this to be possible as it is much more concise than
Position * pos = static_cast<Position *>(GetComponent(eid, POSITION));
(which does work)
Thanks for any help!
EDIT: Here is the full source to prove that its not the function, but something to do with the template...
//EntityManager.h
template<typename T>
T * GetComponent(EID _entity, CType _type);
//EntityManager.cpp
template<typename T>
T * EntityManager::GetComponent(EID _entity, CType _type)
{
T * component = nullptr;
int index = GetComponentIndex(_entity, _type);
if (index >= 0)
component = m_entities.find(_entity)->second[index];
return component;
}
//Main.cpp
EntityManager EM;
Position * pos = EM.GetComponent<Position>(eid, POSITION);
struct Position inherits from struct Component
As I said, the function works flawlessly if I remove the template and replace "T" with "Component" then static_cast the return value. I want to avoid having to use the static cast
EDIT EDIT...
This compiles:
//EntityManager.h
class EntityManager
{
public:
Component * GetComponent();
};
//EntityManager.cpp
Component * EntityManager::GetComponent()
{
return new Position;
}
//Main.cpp
EntityManager EM;
Position * pos = static_cast<Position *>(EM.GetComponent());
This does not:
//EntityManager.h
class EntityManager
{
public:
template<typename T>
T * GetComponent();
};
//EntityManager.cpp
template<typename T>
T * EntityManager::GetComponent()
{
return new T;
}
//Main.cpp
EntityManager EM;
Position * pos = EM.GetComponent<Position>();
WHY? All I'm asking is what format the template should be in.
(Yes, I tested this simplified example, please don't nitpick syntax)