Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force use of curiously recurring template pattern in C++

I have the following base template class.

template<typename T>
class Base {
  public:
    void do_something() {
    }
};

It is intended to be used as a curiously recurring template pattern. It should be inherited like class B : public Base<B>. It must not be inherited like class B : public Base<SomeoneElse>. I want to statically enforce this requirement. If someone uses this wrong, I expect an error in the compiling phase.

What I'm doing is putting a static_cast<T const&>(*this) in do_something(). This way the class inheriting the template is or inherits from the class provided as the template parameter. Sorry for the confusing expression. In plain English, it requires B is or inherits from SomeoneElse in class B : public Base<SomeoneElse>.

I don't know if it's the optimal way to achieve this. Looks gross to me.

However I want to do more. I want to ensure B is SomeoneElse itself. How can I do that?

like image 901
Hot.PxL Avatar asked May 14 '15 07:05

Hot.PxL


1 Answers

Make the constructor (or destructor) of Base private, and then make T a friend. This way the only thing that can construct/destruct a Base<T> is a T.

like image 164
T.C. Avatar answered Nov 14 '22 22:11

T.C.