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

标签 c++ templates pointers static static-members

我正在尝试做的事情:

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

我的问题:

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

代码(部分省略)

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

其他数据:

  • 使用CodeBlocks制作,使用MinGW在c++14模式下编译。

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

最佳答案

由于您正在处理模板,因此您应该在 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;

这是确保 componentRegistry 的最简单方法为每个 ComponentTable<t> 实例化.

关于c++无法将父类指针作为类型定义对静态模板成员的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48823642/

相关文章:

在 C++ 中具有多个枚举参数的 C++ 函数模板部分特化?

c++ - 将指向外部类模板成员函数的指针传递给嵌套类

通过指针和地址复制对象

c++ - 如何更改automake的CXXLINK中的顺序?

c++ - 以下代码的符合 ISO C++ 标准的结果

c++ - 在 C++ 中实现逐行文件解析器时遇到问题

c++ - IGL错误: undefined symbols for architecture x86_64

html - 如果元标记出现在文档正文中会怎样?

c++ - 删除char的正确方法是什么**

c - 需要获取父指针值,最好的方法是什么