【问题标题】:c++ cant define a reference to static template member with the parent class pointer as a typec++ 不能用父类指针作为类型定义对静态模板成员的引用
【发布时间】: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&lt;t&gt;*
  • 检查头文件和 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&lt;t&gt;。
  • @Someprogrammerdude 正如您在“我尝试过的”部分中看到的那样,我已经尝试将其更改为 ComponentTable 并获得相同的结果
  • 至于你的错误,可能与这个问题背后的原因相同:Why can templates only be implemented in the header file?
  • @Someprogrammerdude 只有在我还没有将所有代码都放在标题中时才可行?我没有在 cpp 文件中放置任何函数定义,因此该帖子没有提出可行的解决方案?我知道根可能是相同的(编译器无法正确实例化),但我看不出如何将该解决方案应用于我的问题?

标签: c++ templates pointers static static-members


【解决方案1】:

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

//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&lt;t&gt; 实例化componentRegistry 的最简单方法。

【讨论】:

  • 当同一个 在多个翻译单元中实例化时,这不会破坏 ODR 吗?
  • @TheVee 不,不会的。我不记得背后的理由,但它不会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
相关资源
最近更新 更多