Curiously recurring template pattern
In software engineering, the curiously recurring template pattern (CRTP), is a software design pattern where a base class template is instantiated with a derived class type as its template parameter. The name of the pattern was coined by Coplien[1], who had observed it in some of the earliest C++ template code.
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 derived : base<derived> { void implementation(); };
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 [[2]] and [[3]] libraries.
To be more explicit about the above example, let us consider the case where we have a base class with no virtual functions. Whenever the base class calls another member function, it will always call it's own base class functions. When we inherit from this class, a derived class, we inherit all the member variables and member functions that weren't overridden (no constructors or destructors, of course, either). If the derived class calls an inherited function that then calls another member function, it will never call any derived member functions. As a result of this behaviour, most C++ programmers define member functions as virtual to avoid this problem.
However, if the base class uses the CRTP pattern above for all member function calls, the overrident member functions will get used at compile time. This effectively emulates the virtual function call system without the costs in size or function call overhead (VTBL structures, and method lookups, multiple-inheritance VTBL machinery).
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)