实现 CRTP 链表混合C++

Implementing a CRTP linked list mix-in C++

本文关键字:C++ 混合 链表 CRTP 实现      更新时间:2023-10-16

我无法让CRTP混合工作。

以下是精简的实现:

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

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

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

第二个问题是您尝试继承父模板中的T。这在 CRTP 中是不可能的,因为在实例化模板时,类型将不完整。无论如何,这都会导致无限递归继承:itsybase继承AutoSList<itsybase>继承itsybase继承AutoSList<itsybase>......

正如

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.