我不断收到链接错误,返回一个结构指针,当我这样做:从模板功能
//function declaration
template<typename T>
T * EntityManager::GetComponent(EID _entity, CType _type)
//Main.cpp
Position * pos = GetComponent<Position>(eid, POSITION);
错误LNK2019解析的外部符号“公用:结构位置* __thiscall的EntityManager :: GetComponent(unsigned int类型,枚举CTYPE) “ (?? $ @ GetComponent @@@ UPosition EntityManager的@@ QAEPAUPosition @@ IW4CType @@@ Z) 函数引用_main
我认为错误在于” ST Ruct位置* GetComponent(...)“ 我不希望它返回一个”结构位置指针“ 我希望它返回一个”位置指针!“ 我已经试过各种模板序跋,如“类”和“结构”
我想这是可能的,因为它比
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);
结构的位置,从结构组件
正如我所说的继承,如果我删除模板并将“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>();
为什么? 所有我问的是应该是什么格式的模板。
(是的,我测试了这个简化的例子,请不要鸡蛋里挑骨头的语法)
在我看来,这不是由于返回类型,而是由于它没有在正确的位置找到模板的主体。你在哪里定义身体?它需要在某个地方可以看到它在哪里使用,通常在头文件中 – jcoder
什么是EntityManager?它是一个类还是一个命名空间?为什么它不会在你的“main”调用中出现? –
您是否定义了该功能?在头文件中? – emlai