Quick Q: Prevent user from derive from incorrect CRTP base

Quick A: Make it impossible to construct a class of the wrong type.

Recently on SO:

Prevent user from derive from incorrect CRTP base

1) make all constructors of Base private (if there are no constructors, add one)

2) declare Derived template parameter as friend of Base

template <class Derived>
class Base
{
private:

  Base(){}; // prevent undesirable inheritance making ctor private
  friend  Derived; // allow inheritance for Derived

public :

  void call ()
  {
      static_cast<Derived *>(this)->call_impl();
  }
};

After this it would be impossible to create any instances of the wrong inherited D2.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.