【问题标题】:Implementing a CRTP linked list mix-in C++实现一个 CRTP 链表混合 C++
【发布时间】:2015-02-25 14:08:58
【问题描述】:

我无法让 CRTP mixin 工作。

这里是精简的实现:

template < typename T >
class AutoSList : public T {
public:
  AutoSList() {}

  ~AutoSList() : _next(nullptr) {}


private:
  static T* _head;
  static T* _tail;
  T* _next;

};

// I really hate this syntax.
template <typename T>
T*  AutoSList<T>::_head = nullptr;
template <typename T>
T*  AutoSList<T>::_tail = nullptr;

class itsybase : public AutoSList < itsybase >
{

};

我正在使用 VS2013 并收到以下错误:

   error C2504: 'itsybase' : base class undefined
 : see reference to class template instantiation 'AutoSList<itsybase>' being compiled

我不知道出了什么问题,有什么建议吗?

【问题讨论】:

  • 这是一个错字。您的类名是 AutoSList,但您声明了一个名为 AutoList 的构造函数。与析构函数相同。
  • @AllanDeutsch:请不要在发布答案后更改代码或问题的其他部分。这很容易使答案无效。相反,如果必须,请在问题中添加,但如果该信息使其非常不同,请提出问题。

标签: c++ templates mixins crtp


【解决方案1】:

有 2 个问题导致了这些编译错误。首先是一个拼写错误,导致 c-tor/d-tor 和类名不匹配。

第二个问题是你试图继承父模板中的T。这在 CRTP 中是不可能的,因为在模板被实例化时类型还不完整。无论如何,这将导致无限递归继承:itsybase 继承 AutoSList&lt;itsybase&gt; 继承 itsybase 继承 AutoSList&lt;itsybase&gt;...

【讨论】:

【解决方案2】:

这是一个错字,正如user2079303 所建议的那样。以下是clang++ 对此的评价:

$ clang++ -std=c++11 -c go.cpp 
go.cpp:6:5: error: missing return type for function 'AutoList'; did you mean the constructor name 'AutoSList'?
    AutoList() {}
    ^~~~~~~~
    AutoSList
go.cpp:8:6: error: expected the class name after '~' to name a destructor
    ~AutoList() {}
     ^~~~~~~~
     AutoSList
go.cpp:20:19: error: no member named '_head' in 'AutoSList<T>'
T*  AutoSList<T>::_head = nullptr;
    ~~~~~~~~~~~~~~^
go.cpp:24:25: error: use of undeclared identifier 'ADLib'
class itsybase : public ADLib::AutoSList < itsybase >
                        ^
4 errors generated.

【讨论】:

  • 谢谢,我已经更新它以反映这些更改,但仍然有一些错误。
  • @AllanDeutsch 请在您的问题中明确概述更新,否则您会使答案无效。如果更新提示一个全新的问题,请打开一个新问题。
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2023-01-12
  • 2015-06-03
  • 1970-01-01
相关资源
最近更新 更多