【发布时间】:2018-02-16 09:27:48
【问题描述】:
我想做的事:
为我的班级制作某种“注册表”,以便可以使用唯一的字符串查找每个实例(我正在检查它是否唯一,但在下面的示例中省略了)。
我的问题:
我无法声明对我的静态成员的引用。我不知道为什么。
代码(省略部分)
//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模式下编译。
我希望这些信息足以帮助我;)
【问题讨论】:
-
您使用
ComponentTable*作为componentRegistry映射中的数据。但是ComponentTable不是一个类型,它是一个模板。您只能通过传递模板参数从ComponentTable获取类型,例如ComponentTable<t>。 -
@Someprogrammerdude 正如您在“我尝试过的”部分中看到的那样,我已经尝试将其更改为 ComponentTable
并获得相同的结果 -
至于你的错误,可能与这个问题背后的原因相同:Why can templates only be implemented in the header file?
-
@Someprogrammerdude 只有在我还没有将所有代码都放在标题中时才可行?我没有在 cpp 文件中放置任何函数定义,因此该帖子没有提出可行的解决方案?我知道根可能是相同的(编译器无法正确实例化),但我看不出如何将该解决方案应用于我的问题?
标签: c++ templates pointers static static-members