从模板化函数

时间:2015-10-06 07:03:45

标签: c++ templates pointers struct

执行此操作时,我一直收到链接器错误:

//function declaration
template<typename T>
T * EntityManager::GetComponent(EID _entity, CType _type)

//Main.cpp
Position * pos = GetComponent<Position>(eid, POSITION);
  

错误LNK2019未解析的外部符号“public:struct Position *   __thiscall EntityManager :: GetComponent(unsigned int,enum CType)“   (?? $ @ GetComponent @@@ UPosition EntityManager的@@ QAEPAUPosition @@ IW4CType @@@ Z)   在函数_main

中引用

我相信错误存在于“struct Position * GetComponent(...)”中 我不希望它返回“struct Position指针” 我希望它返回一个“位置指针!” 我尝试了各种模板前言,如“class”和“struct”

我希望这是可能的,因为它比

更简洁
Position * pos = static_cast<Position *>(GetComponent(eid, POSITION));

(确实有效)

感谢您的帮助!

编辑: 以下是证明其不是函数的完整来源,而是与模板有关...

//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继承自struct Component

正如我所说,如果我删除模板并将“T”替换为“Component”然后static_cast返回值,该函数将完美运行。我想避免使用静态演员

编辑编辑......

编译:

//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());

这不是:

//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>();

为什么? 我要问的是模板的格式应该是什么。

(是的,我测试了这个简化的例子,请不要挑剔语法)

1 个答案:

答案 0 :(得分:1)

您不能像使用非泛型类那样在使用通用模板的类中分隔声明和定义。

尝试将您的所有EntityManager.cpp移至EntityManager.h