gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:04:34 25 4
gpt4 key购买 nike

我正在尝试做的事情:

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

我的问题:

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

代码(部分省略)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com