CRTP
CRTP is the curiously recurring template pattern: a base class template takes the derived class as its parameter, template<class D> struct Base { ... }; class Derived : public Base<Derived>. The base can call derived methods as static, inlined calls with no vtable.
Detailed Explanation
A virtual function says "I will call something the derived class writes, and I will decide which one at runtime". That costs a vptr and an indirect call. When the derived type is known at compile time, you can get the same "base code plus derived hook" structure without those costs. CRTP is that structure.
Base<Derived> is a different type for each Derived. Inside Base, static_cast<Derived*>(this) is a downcast the compiler can prove, because the only objects of type Base<Derived> are Derived objects (if you follow the pattern). The base calls derived().hook() and the call is a direct Derived::hook. It can be inlined. There is no virtual.
That is static polymorphism. std::sort plus a comparator is another form. CRTP is the form that still looks like inheritance: shared implementation in the base, customisation points in the derived class.
Typical uses:
- Mixins.
enable_shared_from_this<T>is CRTP. The base needs to knowTso it can returnshared_ptr<T>. - Static interface checks. The base calls
derived().read(); ifDerivedhas noread, instantiation fails. - Operators generated from a core.
InequalityHelper<D>implements!=from==by callingderived().operator==. - Counter or registry per type.
Counted<D>increments astaticcounter unique to eachD.
Compare with a virtual template method: the virtual version lets you store Base* to mixed derived types. CRTP does not. Base<Circle>* and Base<Square>* are unrelated types. If you need a heterogeneous container, use virtuals (or type erasure). If you need a mixin compiled into each type, use CRTP.
C++23 adds "deducing this" (void f(this auto& self)), which covers some CRTP cases without a base template. CRTP remains the pattern you will see in C++11–20 libraries and in enable_shared_from_this.
Construction caveat: during Base's constructor, the Derived part is not yet constructed. Do not call derived().hook() from Base(). The same rule as virtuals, for the same lifetime reason, even though the call is not virtual.
A derived class that inherits the wrong parameter (class Circle : public Base<Square>) compiles until a hook is called, then you have a bad cast. Some code adds a private constructor in the base and friends D, so only D can construct Base<D>.
Code Examples
#include <iostream>
template <typename D>
struct Writer {
void log(const char* msg) {
static_cast<D*>(this)->writeLine(msg); // direct call to D
}
};
struct Console : Writer<Console> {
void writeLine(const char* msg) { std::cout << msg << '\n'; }
};
int main() {
Console c;
c.log("ready"); // prints: ready
}#include <iostream>
template <typename D>
struct Equality {
bool operator!=(const D& other) const {
return !static_cast<const D*>(this)->equals(other);
}
};
struct Port : Equality<Port> {
int n;
bool equals(const Port& other) const { return n == other.n; }
};
int main() {
Port a{80};
Port b{443};
std::cout << std::boolalpha << (a != b) << '\n'; // prints: true
}Common Gotchas
Calling a derived hook from the CRTP base constructor
`Derived`'s members are not initialised yet. The cast is valid as a pointer value; the object is not.
No common base type
you cannot put `Writer<Console>` and `Writer<File>` in one `vector` without a separate virtual interface. CRTP does not replace runtime polymorphism.
Wrong template argument
`class A : public Base<B>` is a silent footgun. Constrain with a private constructor or a concept that `D` is derived from `Base<D>`.
`enable_shared_from_this<T>` is CRTP
you must inherit `enable_shared_from_this<YourClass>`, not a base of it, or `shared_from_this()` will not find the control block.