繁体   English   中英

c ++不能定义对静态模板成员的引用,父类指针作为类型

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

我正在尝试做的事情:

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

我的问题:

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

代码(部分省略)

//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::pair 的 insert 函数进行插入。

其他数据:

  • 使用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的最简单方法。

暂无
暂无

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

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