从模板化函数返回一个结构指针

Return a struct pointer from templated function

本文关键字:一个 结构 指针 函数 返回      更新时间:2023-10-16

当我这样做时,我一直收到链接器错误:

//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(…)"我不想让它返回一个"结构体位置指针"我想让它返回一个"位置指针!"我已经尝试了各种模板序言,如"class"answers"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);

结构Position继承自结构Component

正如我所说,如果我删除模板并将"T"替换为"Component",那么函数将完美地工作,然后将返回值进行静态强制转换。我想避免使用静态强制转换

编辑编辑…

这个编译:

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

为什么?所有我问的是什么格式的模板应该在。

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

在使用泛型模板的类中,不能像在非泛型类中那样将声明和定义分开。

尝试将所有的EntityManager.cpp移动到EntityManager.h

相关文章: