繁体   English   中英

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

[英]Return a struct pointer from templated function

当我这样做时,我不断收到链接器错误:

//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 pointer”我希望它返回一个“Position pointer!” 我尝试过各种模板前言,例如“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”替换为“组件”然后 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>();

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM