Home > database >  enable templated base class only for derived classes
enable templated base class only for derived classes

Time:09-18

How would I go about doing the equivalent of the following?

template < class T, typename = std::enable_if< std::is_base_of< Self, T >::value > > // Can not use std::is_base_of on self
class Self {
protected:
    typedef T self;
};

class ValidDerived : public Self< ValidDerived > { }; // This should compile because T is itself

class InvalidDerived : public Self< ValidDerived > { }; // This should not compile because T is not itself

I'm trying to implement reflection and to do that one of the steps I have to make is getting the typeid( self ).name() of the most-derived class.

CodePudding user response:

In CRTP, T is incomplete in class MyClass : Self<MyClass> {};.

You can add an extra check in a method which should be called/instantiated (such as constructor/destructor):

template<class T>
class Self
{
protected:
    using self = T;

    Self() { static_assert(std::is_base_of<Self, T >::value); }
};
  • Related