skip to content

In C++, what is the curiously recurring template pattern, and how does its base class call a member of the derived class?

level: juniorimportance: should knowfreq 52%

answer

  1. a base that knows its child
  2. the class names itself as an argument
  3. downcast in the base's member function
  4. bound at compile time, no vtable

basics

~20 s

The curiously recurring template pattern (CRTP) is a class deriving from a base template instantiated with itself, as in struct Vec2 : VecOps<Vec2>. The base casts *this to Derived& with static_cast and calls derived members directly, without virtual functions.

solid answer

~40 s

CRTP is a class template, say `VecOps<Derived>`, that expects its argument to be the class inheriting from it: `struct Vec2 : VecOps<Vec2>`. Inside its member functions the base writes `static_cast<Derived&>(*this)` (or the `const` form) to turn its own subobject into the full `Vec2` and then calls `Vec2`'s members by name. Because the type is known at compile time, the call is an ordinary non-virtual call the compiler can inline: no vtable, no vptr in the object. It works even though `Vec2` is incomplete when `VecOps<Vec2>` is instantiated, because member function bodies are only instantiated when used, by which time `Vec2` is complete. The catch is that the base's class body itself cannot use `Derived`'s members, such as its nested types.

code

cpp · 24 lines
cpp
#include <iostream>

template <class Derived>
struct VecOps {
    friend Derived operator+(Derived a, const Derived& b) { return a += b; }
    Derived scaled(double k) const {
        Derived r = static_cast<const Derived&>(*this);  // base reaches the derived object
        r *= k;                                          // calls Derived::operator*=, no virtual
        return r;
    }
};

struct Vec2 : VecOps<Vec2> {
    double x = 0, y = 0;
    Vec2(double x_, double y_) : x(x_), y(y_) {}
    Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; }
    Vec2& operator*=(double k) { x *= k; y *= k; return *this; }
};

int main() {
    Vec2 a{1, 2}, b{3, 4};
    Vec2 c = (a + b).scaled(0.5);
    std::cout << c.x << ' ' << c.y << '\n';  // 2 3
}

go deeper

for a junior

Recall the shape X : Base<X> and the cast static_cast<Derived&>(*this) inside the base. Say that the call is resolved at compile time and needs no virtual function.

for a middle

Explain why the incomplete derived class is acceptable: member bodies are instantiated on use. Name what the base cannot do in its class body, such as reading the derived class's nested types.

for a senior

Point to a real use such as std::ranges::view_interface and say what the cast assumes: the object really is that derived type, or the behaviour is undefined.

for a principal

Frame CRTP as a code-reuse tool rather than an interface: each derived type gets its own base class, so it suits mixing in members, not runtime substitution.

## The shape of the pattern The **curiously recurring template pattern (CRTP)** is a way for a base class to call into the class that derives from it without any virtual function. It has three parts: - **The base** is a class template whose parameter, conventionally called `Derived` or `D`, names the class that will inherit from it. - **The derived class** names *itself* as that argument in its own base list: `struct Vec2 : VecOps<Vec2>`. That self-reference is the "curiously recurring" part. - **The link** is a downcast inside the base's member functions: `static_cast<Derived&>(*this)` turns the base subobject back into the whole derived object. A numeric vector library uses it to write operators once. `VecOps<Derived>` defines `operator+` in terms of the derived type's own `operator+=`, and a `scaled(k)` member in terms of its `operator*=`. Every vector type that derives from `VecOps<ItsOwnName>` gets those members, each generated for its exact type. ## How the base reaches the derived object Inside `VecOps<Vec2>`, the expression `*this` has type `VecOps<Vec2>&`. The standard lets `static_cast` convert a reference to a base into a reference to a class derived from it, provided the derived class is complete and the base is not a virtual base. If the object really is the base subobject of a `Vec2`, the result refers to that `Vec2`; if it is not, the behaviour is undefined. Nothing is checked at run time, unlike `dynamic_cast`, and nothing needs a vtable. After the cast, a call like `self *= k` is an ordinary call to `Vec2::operator*=`, bound by the compiler while it instantiates `VecOps<Vec2>::scaled`. That is why CRTP is called **static polymorphism**: the base's code behaves differently for each derived class, but the choice is made per instantiation, at compile time, and the call can be inlined. ## Why an incomplete class is enough When the compiler reads `struct Vec2 : VecOps<Vec2>`, `Vec2` is still incomplete, yet `VecOps<Vec2>` has to be instantiated to become a base. This works because instantiating a class template specialization instantiates the **declarations** of its member functions but not their **definitions**. The body of `scaled`, with its cast to `Vec2&`, is instantiated only when something calls it, and by then `Vec2` is complete. The same rule marks what the base cannot do. Anything in the base's class body, as opposed to a member function body, is instantiated while `Derived` is incomplete: 1. a member alias such as `using value_type = typename Derived::value_type;` 2. a data member or array sized with `sizeof(Derived)` 3. a member function whose declared return type names a member of `Derived` ```cpp template <class Derived> struct VecOps { using value_type = typename Derived::value_type; // instantiated with the class }; struct Vec3 : VecOps<Vec3> { using value_type = float; }; ``` Apple clang 21 rejects this with `error: no type named 'value_type' in 'Vec3'`, because `Vec3` has no members yet at that point. The usual repairs are to pass the needed type as a second template argument (`VecOps<Vec3, float>`), or to let a member function deduce its return type with `auto`, which is resolved only when its definition is instantiated. ## Where the standard library uses it - `std::ranges::view_interface<D>` (C++20) is the textbook case. A view class derives from `view_interface<MyView>` and gets `empty()`, `operator bool`, `front()`, `back()`, `size()` and `operator[]` where its iterators support them, all written in terms of its own `begin()` and `end()`. The draft states that `D` may be an incomplete type and that it must be complete, and derive from `view_interface<D>`, before any member other than a special member function is referenced. - `std::enable_shared_from_this<T>` also takes the deriving class as its argument, so `shared_from_this()` can return `std::shared_ptr<T>`; its ownership rules belong with shared pointers. ## A common refinement: a self() helper Writing the cast in every member gets noisy, so CRTP bases usually wrap it in a pair of private helpers: ```cpp Derived& self() { return static_cast<Derived&>(*this); } const Derived& self() const { return static_cast<const Derived&>(*this); } ``` The `const` overload matters: inside a `const` member function `*this` is `const VecOps<Derived>&`, and casting it to a non-`const` `Derived&` is ill-formed, so the cast must keep the qualifier. The C++ draft writes `view_interface` exactly this way, with an exposition-only private member performing `static_cast<D&>(*this)` and a `const` twin. ## What to say in an interview Give the shape (`X : Base<X>`), the mechanism (`static_cast<Derived&>(*this)`), the payoff (calls resolved at compile time, no vptr) and one limit (the base's class body cannot see `Derived`'s members). That covers what the question is testing; trade-offs against virtual functions and the C++23 alternative are natural follow-ups.

  • Why can the CRTP base use Derived in a member function body but not in a member alias?
    Instantiating `VecOps<Vec2>` as a base happens while `Vec2` is still incomplete. That instantiation covers the class body and member declarations, so `typename Derived::value_type` there fails. Member function definitions are instantiated only when called, after `Vec2` is complete, so a cast and member calls inside a body are fine. Pass the type as an extra template argument when the base needs it in its declarations.
  • What happens if the derived member the CRTP base calls does not exist?
    The program fails to compile when the base's member function that makes the call is instantiated, that is, when someone calls it for that derived type. The error names the missing member in the derived class. If nothing calls that base member, nothing is instantiated and no error appears, which is why CRTP interfaces can be incomplete without anyone noticing until first use.

A form letter with a blank for the recipient's name: the template is written once, and each copy is filled in for one specific person before it is sent, so nobody looks up the name at delivery time.

  • CRTP uses virtual functions under the hood to reach the derived class.
  • The base should use dynamic_cast to reach the derived object.
  • The derived class must be complete before the base template is instantiated.
  • The base can read Derived's nested typedefs in its own class body.
  • Vec2 and Vec3 deriving from VecOps share one common base class.