Search code examples
c++c++11crtpstatic-assert

How to secure CRTP against providing wrong superclass?


In the curiously recurring template pattern, we write

template <class Derived>
class Base {
};

class Derived : public Base<Derived> {
};

What would be a good way to make the code robust another copy-paste omissions, so that the following snippet throws a compile-time error:

class AnotherDerived : public Base<Derived> {
};

I'm using Visual C++ 2013.


Solution

  • Make Base's destructor private, and then make Derived a friend of Base<Derived>:

    template <class Derived>
    class Base {
        private: ~Base() = default;
        friend Derived;
    };
    
    class Derived : public Base<Derived> {
    };
    

    This does not actually make doing

    class AnotherDerived : public Base<Derived> {
    };
    

    illegal, but any attempt to actually construct an AnotherDerived will fail.