c++ 无法使用 parent class 指针定义对静态模板成员的引用作为类型

c++ cant define a reference to static template member with the parent class pointer as a type

我想做什么:

为我的 class 做一些 "Registry" 这样每个实例都可以使用唯一的字符串查找(我正在检查它是否唯一但在下面的示例中被省略) .

我的问题:

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

代码(部分省略)

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

我已经试过了

我真的没有在这方面取得领先,所以我不能尝试太多:(

错误:

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

这出现在我试图首先使用构造函数中的成员的地方。我正在使用具有正确类型的简单 std::pair 的插入函数进行插入。

其他数据:

我希望这些信息足以帮助我解决问题 ;)

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

//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 的最简单方法