Curiously recurring template pattern
Appearance
A term due to Coplien [1], who had observed it in some of the earliest C++ template code. In the Curiously Recurring Template Pattern (CRTP), a base class template is instantiated with a derived class type as its template parameter:
Example
// The Curiously Recurring Template Pattern (CRTP) struct derived : base<Derived> { // ... };
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 static_cast, e.g.:
template <class Derived> struct base { void interface() { // ... static_cast<Derived*>(this)->implementation(); // ... } };
// ...
struct my_derived : base<my_derived> { void implementation() { ... } };
This technique achieves a similar effect to the use of virtual functions, without the costs (and some flexibility) of dynamic polymorphism.
See Also
References
- Coplien, James O. (1995, February). "Curiously Recurring Template Patterns". C++ Report: 24–27.
{{cite journal}}
: Check date values in:|year=
(help)CS1 maint: year (link)