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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.