cpp / expert
Snippet
The Curiously Recurring Template Pattern (CRTP)
CRTP is a technique where a class derives from a template instantiation using itself as an argument. It enables static polymorphism (compile-time dispatch), which avoids the overhead of virtual function tables (vtable).
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
template <typename Derived>class Base {public:void interface() {static_cast<Derived*>(this)->implementation();}};class Derived : public Base<Derived> {public:void implementation() { /* ... */ }};
Breakdown
1
static_cast<Derived*>(this)
Casts the base pointer to the derived type to access specific implementations at compile time.
2
class Derived : public Base<Derived>
The 'Curiously Recurring' part: the class passes itself to its own base.