简体   繁体   中英

Implementing a CRTP linked list mix-in C++

I'm having trouble getting a CRTP mixin to work.

Here is the stripped down implementation:

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

};

I'm using VS2013 and getting the following errors:

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

I have no idea what's going wrong, any suggestions?

There's 2 problems causing those compilation errors. First is a typo causing mismatch with c-tor/d-tor and class name.

The second problem is that you're trying to inherit T in the parent template. That's not possible in CRTP because the type will not be complete by the time the template is instantiated. That would cause an infinitely recursive inheritance anyway: itsybase inherits AutoSList<itsybase> which inherits itsybase which inherits AutoSList<itsybase> ...

It's a typo, as user2079303 suggested. Here's what clang++ says about it:

$ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM