Curiously recurring template pattern


The curiously recurring template pattern is an idiom in C++ in which a class X derives from a class template instantiation using X itself as template argument. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

History

The technique was formalized in 1989 as "F-bounded quantification." The name "CRTP" was independently coined by Jim Coplien in 1995, who had observed it in some of the earliest C++ template code
as well as in code examples that Timothy Budd created in his multiparadigm language Leda. It is sometimes called "Upside-Down Inheritance" due to the way it allows class hierarchies to be extended by substituting different base classes.
The Microsoft Implementation of CRTP in Active Template Library was independently discovered, also in 1995, by Jan Falkin, who accidentally derived a base class from a derived class. Christian Beaumont first saw Jan's code and initially thought it couldn't possibly compile in the Microsoft compiler available at the time. Following the revelation that it did indeed work, Christian based the entire ATL and Windows Template Library design on this mistake.

General form


// The Curiously Recurring Template Pattern
template
class Base
class Derived : public Base

Some use cases for this pattern are static polymorphism and other metaprogramming techniques such as those described by Andrei Alexandrescu in Modern C++ Design.
It also figures prominently in the C++ implementation of the Data, Context, and Interaction paradigm.

Static polymorphism

Typically, the base class template will take advantage of the fact that member function bodies are not instantiated until long after their declarations, and will use members of the derived class within its own member functions, via the use of a cast; e.g.:

template
struct Base
struct Derived : Base

In the above example, note in particular that the function Base::interface, though declared before the existence of the struct Derived is known by the compiler, is not actually instantiated by the compiler until it is actually called by some later code which occurs after the declaration of Derived, so that at the time the function "implementation" is instantiated, the declaration of Derived::implementation is known.
This technique achieves a similar effect to the use of virtual functions, without the costs of dynamic polymorphism. This particular use of the CRTP has been called "simulated dynamic binding" by some. This pattern is used extensively in the Windows ATL and WTL libraries.
To elaborate on the above example, consider a base class with no virtual functions. Whenever the base class calls another member function, it will always call its own base class functions. When we derive a class from this base class, we inherit all the member variables and member functions that weren't overridden. If the derived class calls an inherited function which then calls another member function, that function will never call any derived or overridden member functions in the derived class.
However, if base class member functions use CRTP for all member function calls, the overridden functions in the derived class will be selected at compile time. This effectively emulates the virtual function call system at compile time without the costs in size or function call overhead at the disadvantage of not being able to make this choice at runtime.

Object counter

The main purpose of an object counter is retrieving statistics of object creation and destruction for a given class. This can be easily solved using CRTP:

template
struct counter
template int counter::objects_created;
template int counter::objects_alive;
class X : counter
class Y : counter

Each time an object of class X is created, the constructor of counter is called, incrementing both the created and alive count. Each time an object of class X is destroyed, the alive count is decremented. It is important to note that counter and counter are two separate classes and this is why they will keep separate counts of X's and Y's. In this example of CRTP, this distinction of classes is the only use of the template parameter and the reason why we cannot use a simple un-templated base class.

Polymorphic chaining

, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.
When the named parameter object pattern is applied to an object hierarchy, things can go wrong. Suppose we have such a base class:

class Printer

Prints can be easily chained:

Printer.println.println;

However, if we define the following derived class:

class CoutPrinter : public Printer

we "lose" the concrete class as soon as we invoke a function of the base:

// v----- we have a 'Printer' here, not a 'CoutPrinter'
CoutPrinter.print.SetConsoleColor.println; // compile error

This happens because 'print' is a function of the base - 'Printer' - and then it returns a 'Printer' instance.
The CRTP can be used to avoid such problem and to implement "Polymorphic chaining":

// Base class
template
class Printer
// Derived class
class CoutPrinter : public Printer
// usage
CoutPrinter.print.SetConsoleColor.println;

Polymorphic copy construction

When using polymorphism, one sometimes needs to create copies of objects by the base class pointer. A commonly used idiom for this is adding a virtual clone function that is defined in every derived class. The CRTP can be used to avoid having to duplicate that function or other similar functions in every derived class.

// Base class has a pure virtual function for cloning
class AbstractShape ;
// This CRTP class implements clone for Derived
template
class Shape : public AbstractShape ;
// Every derived class inherits from CRTP class instead of abstract class
class Square : public Shape;
class Circle : public Shape;

This allows obtaining copies of squares, circles or any other shapes by shapePtr->clone.

Pitfalls

One issue with static polymorphism is that without using a general base class like AbstractShape from the above example, derived classes cannot be stored homogeneously--that is, putting different types derived from the same base class in the same container. For example, a container defined as std::vector does not work because Shape is not a class, but a template needing specialization. A container defined as std::vector*> can only store Circles, not Squares. This is because each of the classes derived from the CRTP base class Shape is a unique type. A common solution to this problem is to inherit from a shared base class with a virtual destructor, like the AbstractShape example above, allowing for the creation of a std::vector.