从模板化函数返回一个结构指针
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(…)"我不想让它返回一个"结构体位置指针"我想让它返回一个"位置指针!"我已经尝试了各种模板序言,如"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
。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 如何在级别上打印树,给定一个结构,该结构保存节点的值及其父节点的值,对于树中的每个节点
- 创建一个结构的关联数组,以创建一个缓冲区,供键快速访问
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 我想重置一个C++结构统计,我可以以某种方式使用 stat() 语法吗?
- C++可以输出一个结构的内存地址吗
- 通过 C++ 中的另一个结构成员访问结构
- C++ push_back() 一个结构体到一个向量中
- 难以从另一个结构中的函数返回结构
- 如何将向量添加到结构中以创建一个库存系统,在该系统中,我可以仅使用一个结构向系统添加多种不同的葡萄酒
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 是否可以在同一未创建的结构内创建一个结构