More C++ Idioms/Curiously Recurring Template Pattern

= Curiously Recurring Template Pattern =

Intent
Specialize a base class using the derived class as a template argument.

Also Known As

 * CRTP
 * Mixin-from-above
 * Static polymorphism
 * Simulated dynamic binding
 * Upside-down Inheritance

Motivation
To extract out a type independent but type customizable functionality in a base class and to mix-in that interface/property/behavior into a derived class, customized for the derived class.

Solution and Sample Code
In CRTP idiom, a class T inherits from a template that specializes on T. This is valid only if the size of X can be determined independently of T. Typically, the base class template will take advantage of the fact that member function bodies (definitions) 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, e.g.:

C++23
C++23 added a new feature called explicit object parameter, which allows you to pass the object a method is called on as the first parameter of a method instead of. When calling the method, as with all function calls, upcasts are only performed if necessary, making it possible to change the behavior of a method for derived classes without overriding it by using a method template or. If the CRTP base class you would have written only has non-static methods, this removes the need to pass T as a template parameter, making it similar to deriving from an ordinary base class. One benefit of this approach is that if  is a base class of , the mixin methods of Derived will use   methods rather than   methods. Another is that it makes const and non-const method overloads unnecessary because the explicit object parameter can bind to const and non-const references if a constraint is not used to prevent this.

Known Uses
Barton-Nackman trick

Related Idioms

 * Parameterized Base Class Idiom
 * Barton-Nackman trick