C++: Inherit class from template parameter

c++, design-patterns, inheritance, templates

Solution

It's often used to realize static polymorphism.

Use cases are:

- Policy-based design

- Curiously recurring template pattern

- Barton–Nackman trick

In general you have the benefits from dynamic polymorphism, without the extra runtime costs of virtual functions. But it's only useful if the concrete type can be determined at compile time.

Problem

I recently saw the following C++ code-snippet ``` template <class B> class A : public B { ... }; ``` and I am wondering in which setting such a design is good practice? The way I understand it, is that having the superclass as a template parameter allows users of A to choose a superclass when instantiating an object of A. But if this is the case, wouldn't it be better to have a common superclass C for all the classes (B) which are used as the template argument and have A extend C ?

Original source