【问题标题】:Return a struct pointer from templated function从模板函数返回结构指针
【发布时间】:2015-10-06 07:03:44
【问题描述】:

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

//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(...)” 我不希望它返回一个“结构位置指针” 我希望它返回一个“位置指针!” 我尝试过各种模板前言,例如“类”和“结构”

我希望这可以实现,因为它比

简洁得多
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?它是一个类还是一个命名空间?为什么它没有出现在您的 main 电话中?
  • 你定义函数了吗?在头文件中?
  • 是的,它是在EntityManager.h中定义的。我只是简化了问题的所有内容。我唯一更改的是在 .h 和 .cpp 文件中的函数上方添加“template”。我用“T”替换了“组件”
  • 当您“简化”示例时,不要删除错误或添加复杂性。那是你的责任,不是我们的。如果您希望我们为您更正您的程序,语义正是我们应该在这里关注的重点。

标签: c++ templates pointers struct


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多