More C++ Idioms/Curiously Recurring Template Pattern
< More C++ IdiomsCuriously Recurring Template Pattern
Intent
Specialize a base class using the derived class as a template argument.
Also Known As
- CRTP
- Mixin-from-above
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.
class T : public X<T> {…};
This is valid only if the size of X<T> 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 static_cast
, e.g.:
template <class Derived>
struct base
{
void interface()
{
// ...
static_cast<Derived*>(this)->implementation();
// ...
}
static void static_interface()
{
// ...
Derived::static_implementation();
// ...
}
// The default implementation may be (if exists) or should be (otherwise)
// overridden by inheriting in derived classes (see below)
void implementation();
static void static_implementation();
};
// The Curiously Recurring Template Pattern (CRTP)
struct derived_1 : base<derived_1>
{
// This class uses base variant of implementation
//void implementation();
// ... and overrides static_implementation
static void static_implementation();
};
struct derived_2 : base<derived_2>
{
// This class overrides implementation
void implementation();
// ... and uses base variant of static_implementation
//static void static_implementation();
};
Known Uses
Related Idioms
References
Curiously Recurring Template Pattern on Wikipedia
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.