The CRTP Idiom
Curiously recurring template pattern.
What Is CRTP?
The Curiously Recurring Template Pattern (CRTP) is a C++ idiom where a class Derived inherits from a template base instantiated with Derived itself.
- Shape:
class Derived : public Base<Derived> - The base learns its derived type at compile time
template <typename T>
class Base {};
class Derived : public Base<Derived> {};The Core Mechanism
Inside the base, you can static_cast the this pointer to the derived type. Because the derived type is a template parameter, this is a fully compile-time cast with no runtime cost.
#include <iostream>
template <typename T>
class Base {
public:
void interface() {
static_cast<T*>(this)->implementation();
}
};
class Derived : public Base<Derived> {
public:
void implementation() { std::cout << "Derived impl\n"; }
};
int main() {
Derived d;
d.interface();
return 0;
}All lessons in this course
- The CRTP Idiom
- Static Polymorphism
- Mixins with CRTP
- When to Use CRTP