The curiously recurring template pattern (CRTP) 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.
The technique was formalized in the 1980s 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.
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.
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 cast; e.g.:
In the above example, note in particular that the function Base<Derived>::implementation(), though declared before the existence of the struct Derived is known by the compiler (i.e., before Derived is declared), is not actually instantiated by the compiler until it is actually called by some later code which occurs after the declaration of Derived (not shown in the above example), 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 (and some flexibility) 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.