Introducing CRTP

Now, we will introduce CRTP, which turns inheritance on its head:

template <typename D> class B {    ...};class D : public B<D> {    ...};

The first change that jumps out is that the base class is now a class template. The derived class still inherits from the base class, but now from the specific instantiation of the base class template—on its own! Class B is instantiated on class D, and class D inherits from that instantiation of class B, which is instantiated on class D, which inherits from class B, which... that's recursion in action. Get used to it because you will see it often in this chapter.

What is the motivation for this mind-twisting pattern? Consider that now the base class has compile-time information about the derived ...

Get Hands-On Design Patterns with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.