C 不能将带有父类指针作为类型的静态模板成员定义引用



我要做的事情:

为我的班级制作某种"注册表",以便可以使用唯一字符串查找每个实例(我正在检查其唯一的,但在下面的示例中省略了(。

我的问题:

我不能声明对我的静态成员的引用。我不知道为什么。

代码(省略零件(

//component.h
template <class t>
class ComponentTable : InstanceCounted<ComponentTable<t>> //Instance Counted is a template that automatically counts the instances
{
private:
    //Omitted
    static std::unordered_map<std::string, ComponentTable*> componentRegistry;
public:
    //Omitted, the insert happens in the constructor and it gets removed in the destructor
}
//component.cpp
template<class t>
std::unordered_map<std::string, ComponentTable<t>*> ComponentTable<t>::componentRegistry;
//---

我已经尝试了

  • ComponentTable*更改为标题中的ComponentTable<t>*
  • 检查标题和CPP文件中的拼写。
  • 重建项目

我真的没有铅,所以我有点尝试:(

错误:

undefined reference to `ComponentTable<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::componentRegistry'|

这将出现在我试图首先使用构造函数中的成员的位置。我正在使用简单的std ::对正确类型的插入函数进行插入。

其他数据:

  • 使用CodeBlocks制造并在C 14模式下使用Mingw编译。

我希望此信息足以帮助我在这里;(

由于您正在处理模板,因此应定义标题本身中的静态成员:

//component.h
template <class t>
class ComponentTable : InstanceCounted<ComponentTable<t>>
{
    static std::unordered_map<std::string, ComponentTable*> componentRegistry;
};
template<class t>
std::unordered_map<std::string, ComponentTable<t>*> ComponentTable<t>::componentRegistry;

这是确保为每个ComponentTable<t>安装componentRegistry的最简单方法。

最新更新