# CRTP and Deducing This

> Achieve zero-overhead static polymorphism with the Curiously Recurring Template Pattern, then eliminate its boilerplate and fourfold member overloads using C++23 explicit object parameters.

- **Source:** C++ Atlas (https://cppatlas.com/topics/crtp-and-deducing-this)
- **Track:** Templates
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [class.derived] (https://eel.is/c++draft/class.derived), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [class.mfct] (https://eel.is/c++draft/class.mfct), [temp.dep] (https://eel.is/c++draft/temp.dep), [over.match.funcs] (https://eel.is/c++draft/over.match.funcs), [class.mem] (https://eel.is/c++draft/class.mem)
- **cppreference links:** [Curiously Recurring Template Pattern](https://en.cppreference.com/w/cpp/language/crtp), [Non-static member functions](https://en.cppreference.com/w/cpp/language/member_functions), [The this pointer](https://en.cppreference.com/w/cpp/language/this), [Dependent names](https://en.cppreference.com/w/cpp/language/dependent_name), [std::forward_like](https://en.cppreference.com/w/cpp/utility/forward_like), [Empty base optimization](https://en.cppreference.com/w/cpp/language/ebo)
- **Prerequisites:** inheritance-and-virtual-functions, value-categories, forwarding-references-and-perfect-forwarding

When concrete types are known at compile time, virtual dispatch forces unnecessary indirection through a `vptr` and blocks inlining across interfaces. C++ solves static polymorphism via two complementary techniques: the classic **Curiously Recurring Template Pattern** (CRTP) and C++23's **explicit object parameters** (commonly called *deducing `this`*).

## Static polymorphism with CRTP

In CRTP, a derived class `Widget` inherits from a class template `Base<Widget>`, passing its own type as the template argument (`[class.derived]`):

```cpp
template <class Derived>
class CounterMixin {
    friend Derived;
    CounterMixin() = default; // prevents accidental Base<WrongType> inheritance
public:
    void bump() {
        static_cast<Derived&>(*this).on_bump();
    }
    const Derived& self() const {
        return static_cast<const Derived&>(*this);
    }
};

struct Metric : CounterMixin<Metric> {
    int count = 0;
    void on_bump() { ++count; }
};
```

Because `CounterMixin<Metric>` knows the exact type `Metric` at compile time, `static_cast<Derived&>(*this)` resolves to `Metric::on_bump()` statically—with zero `vptr` storage overhead, zero vtable lookup, and full inlining. Standard and production libraries rely on CRTP extensively for mixins (like `std::ranges::view_interface` or `std::enable_shared_from_this`), static interfaces, and empty base optimization (`[class.mem]`).

## Classic CRTP pitfalls: lookup, timing, and friends

Three recurring traps catch authors writing classic CRTP bases:

1. **Wrong template argument copy-paste:** Writing `struct B : CounterMixin<A>` instead of `CounterMixin<B>` causes undefined behavior when `CounterMixin<A>` casts `*this` to `A&`! Guard against this by making `CounterMixin`'s constructor `private` and declaring `friend Derived;`.
2. **Incomplete `Derived` during instantiation:** Inside the class body of `CounterMixin<Metric>`, `Metric` is still an incomplete type while `CounterMixin<Metric>` is being instantiated as `Metric`'s base. Member *function bodies* may reference `Derived` (since function bodies are instantiated lazily upon use), whereas non-static data members or signature return types like `typename Derived::value_type` will fail because `Derived` is not complete yet.
3. **Dependent base name lookup (`[temp.dep]`):** When a class template `Child<T>` inherits from a dependent base `Base<T>`, two-phase lookup does **not** examine `Base<T>` during unqualified lookup. Access base members via `this->member` or `Base<T>::member`.

> **Pitfall.** Never call `static_cast<Derived&>(*this)` inside `Base<Derived>`'s constructor or destructor. When `Base`'s constructor executes, `Derived`'s subobject has not begun its lifetime yet; when `Base`'s destructor runs, `Derived` has already been destroyed. Either access invokes undefined behavior (`[class.cdtor]`).

## C++23 explicit object parameters (Deducing This)

C++23 (`P0847R7`) introduces **explicit object member functions** (`[dcl.fct]`, `[class.mfct]`): instead of an implicit hidden `this` pointer, the first parameter carries the keyword `this` and gives the receiver an explicit name and deducible template type.

Before C++23, wrapper types such as `std::optional` or fluent builders had to write four nearly identical accessor overloads (`&`, `const&`, `&&`, and `const&&`) just to forward a stored member with matching constness and value category. Worse, adding `&` and `&&` ref-qualifiers to a classic CRTP base required duplicating every mixin method too.

> **Mental model.** An explicit object parameter makes the receiver parameter behave like any ordinary function parameter whose type and value category (`&`, `const&`, `&&`, `const&&`, or even derived subclass type `Self`) are deduced straight from the call expression.

Look at how one function template replaces all four accessor overloads—while also deducing cv-qualification and preserving value category on member fields with `std::forward_like`:

```cpp
#include <string>
#include <utility>

struct Cell {
    std::string data;

    template <class Self>
    auto&& value(this Self&& self) {
        return std::forward_like<Self>(self.data);
    }
};
```

Wait—why use `std::forward_like<Self>(self.data)` instead of `std::forward<Self>(self).data`? If `data` were a reference member (`std::string& data;`), `[expr.ref]` dictates that `std::forward<Cell>(self).data` evaluates to an **lvalue** `std::string&` even on an rvalue `Cell&&`, silently blocking moves! `std::forward_like<Self>(self.data)` merges `Self`'s constness and value category directly onto `self.data`, returning `std::string&&` when `self` is a non-const rvalue.

> **Standardese.** Under `[dcl.fct]` and `[class.mfct]`, a member function with an explicit object parameter has **no implicit `this` pointer** inside its body, cannot be `static`, `virtual`, `const`, `volatile`, or ref-qualified (`&`/`&&`), and taking its address yields a **plain function pointer** (`auto fn = &Cell::value<Cell&>;` has type `std::string& (*)(Cell&)`), not a pointer-to-member-function.

## CRTP without templates, recursive lambdas, and pass-by-value this

Because `Self` in `(this Self&& self)` deduces to the actual expression type at the call site—including any **derived class**—CRTP no longer requires making the base class a template at all:

```cpp
struct Printable {
    void print_twice(this auto&& self) {
        self.emit();
        self.emit();
    }
};

struct Badge : Printable {
    int hits = 0;
    void emit() { ++hits; }
};

auto factorial = [](this auto&& self, int n) -> int {
    return n <= 1 ? 1 : n * self(n - 1);
};
```

Look at the cleanup achieved in `Printable` and `factorial`:

- **Non-template CRTP:** `Printable` is an ordinary non-template class; `Badge` simply inherits `Printable`, eliminating `Base<WrongType>` bugs, dependent base lookup issues, and `static_cast<Derived&>(*this)` boilerplate.
- **Recursive lambdas:** Writing `(this auto&& self, int n)` inside a lambda binds `self` directly to the closure object, giving zero-overhead self-recursion without `std::function` type erasure or passing the lambda to itself.
- **Pass-by-value `this`:** Small scalar-like types can declare `void tick(this Counter copy)` to receive `this` in a register by value rather than indirectly by pointer.

Compare the three dispatch mechanisms side by side to choose the right tool:

| Mechanism | Runtime cost | Base template needed? | Eliminates 4x `&`/`&&` overloads? | Heterogeneous container support? |
| --- | --- | --- | --- | --- |
| Virtual dispatch | `vptr` + indirect call | No | No | Yes (`Base*`) |
| Classic CRTP | Zero (static inline) | Yes (`Base<Derived>`) | No | No |
| Deducing `this` (C++23) | Zero (static inline) | No | Yes (`this Self&&`) | No |

Note two remaining boundaries when adopting deducing `this`:

- Inside `Printable::print_twice(this auto&& self)`, calling `self.emit()` respects normal member access rules—so `Badge::emit()` must be `public` (or `Printable` declared a `friend`), whereas private helpers on `Printable` itself require care because `self` carries static type `Badge`, not `Printable`.
- Because overload resolution treats an explicit object parameter like a normal first parameter (`[over.match.funcs]`), a derived class can cleanly shadow or customize behavior without template specialization, while pass-by-value `this` removes aliasing concerns on immutable small handles.

## What to remember

- Classic CRTP achieves zero-overhead static polymorphism via `Base<Derived>` and `static_cast<Derived&>(*this)`, but breaks if `Base` invokes `Derived` during construction/destruction or relies on incomplete members of `Derived`.
- Always guard classic CRTP constructors (`private` + `friend Derived`) to prevent inheriting `Base<WrongType>`, and qualify dependent base members with `this->`.
- C++23 explicit object parameters (`this Self&& self`) eliminate quadrupled `&`/`const&`/`&&`/`const&&` overloads, simplify CRTP into non-template bases, and enable direct recursive lambdas.
- Explicit object functions have no implicit `this`, forbid `virtual`/`static`/`const`/ref-qualifiers, and produce regular function pointers when their address is taken.
- Use `std::forward_like<Self>(self.member)` when returning a member from `this Self&& self` so reference members still respect the owner's constness and rvalue-ness.

## Concept Map Outline

- **CRTP & Deducing This:** Compile-time polymorphism evolved from template base casts to C++23 explicit object parameters.
  - **Classic CRTP:** A derived class passes itself as a template argument to its own base class.
    - **Static Dispatch Cast:** Base invokes derived methods via static_cast<Derived&>(*this) with full inlining.
    - **Zero Vtable Cost:** CRTP avoids vptr memory overhead and indirect runtime calls entirely.
    - **Mixin Injection:** Reusable interfaces like view_interface inject operators onto concrete derived types.
    - **Friend Guard Pattern:** Making Base's constructor private and friending Derived prevents inheriting Base<WrongType>.
  - **CRTP Constraints:** Instantiation order and two-phase lookup create subtle classic CRTP hazards.
    - **Incomplete Derived Type:** Derived is incomplete while Base<Derived> instantiates, restricting uses to member bodies.
    - **Ctor and Dtor UB:** Casting *this to Derived inside Base's constructor or destructor triggers undefined behavior.
    - **Dependent Base Lookup:** Derived templates inheriting dependent bases must access base members via this-> or Base<T>::.
  - **Explicit Object Param:** C++23 lets the receiver parameter be written explicitly with this Self&&.
    - **this Self&& Syntax:** Annotating the first parameter with this deduces both object type and value category.
    - **No Implicit this:** Explicit object member functions forbid using the implicit this pointer inside their body.
    - **Disallowed Qualifiers:** Explicit object parameters cannot be combined with virtual, static, const, or ref-qualifiers.
    - **Plain Function Pointer:** Taking the address of an explicit object function yields a regular function pointer, not a member pointer.
  - **Overload Unification:** A single deducing-this template replaces four cv- and ref-qualified member overloads.
    - **Single Template Body:** One template handles &, const&, &&, and const&& receivers without code duplication.
    - **Deduces Derived Self:** Calling a base explicit-object method on Derived deduces Self directly as Derived.
    - **std::forward_like Member:** Merges Self's constness and value category onto a returned field or reference member.
  - **Modern Idioms:** Deducing this simplifies static mixins, recursive closures, and small value types.
    - **Non-Template CRTP:** Mixins become ordinary non-template bases dispatching to self.impl() cleanly.
    - **Recursive Lambdas:** Naming this auto&& self inside a lambda enables zero-overhead self-recursion.
    - **Pass-By-Value this:** Taking this T copy passes small types directly in registers rather than by pointer.

## Standardese Quiz Questions

### Question 1 [warmup] ([class.derived], [temp.inst])

What primary performance advantage does CRTP offer over virtual dispatch when all concrete types are known at compile time?

A. CRTP lets you store unrelated derived types inside a single std::vector<Base>
B. Calls resolve statically via static_cast with no vptr memory overhead, no vtable lookup, and full inlining
C. CRTP moves object construction onto the stack automatically
D. CRTP allows overriding private virtual functions without virtual destructors

**Answer (B):** Calls resolve statically via static_cast with no vptr memory overhead, no vtable lookup, and full inlining

**Why:** Because Base<Derived> knows the concrete Derived type at compile time, static_cast<Derived&>(*this) resolves calls statically, eliminating the hidden vptr per object and enabling inline optimization.

### Question 2 [warmup] ([dcl.fct], [expr.prim.lambda])

What problem does C++23's explicit object parameter `(this auto&& self)` solve directly inside a lambda expression?

```cpp
auto fib = [](this auto&& self, int n) -> int {
    return n <= 1 ? n : self(n - 1) + self(n - 2);
};
```

A. It makes the lambda capture local variables by move automatically
B. It turns the lambda into a virtual function callable through a base pointer
C. It evaluates every call to the lambda as consteval
D. It lets the lambda call itself recursively without std::function or passing itself as an extra argument

**Answer (D):** It lets the lambda call itself recursively without std::function or passing itself as an extra argument

**Why:** Under [dcl.fct] and [expr.prim.lambda], naming an explicit object parameter `this auto&& self` binds `self` to the lambda's closure object, enabling direct, zero-overhead recursion.

### Question 3 [tricky] ([expr.prim.this], [class.mfct])

Why does the member function `Widget::read` below fail to compile in C++23?

```cpp
struct Widget {
    int count = 5;
    int read(this const Widget& self) {
        return this->count;
    }
};
```

A. Inside an explicit object member function there is no implicit `this` pointer; it must write `self.count`
B. An explicit object parameter cannot be const-qualified as `const Widget&`
C. Explicit object member functions must be templates
D. Members cannot be accessed inside explicit object functions unless declared mutable

**Answer (A):** Inside an explicit object member function there is no implicit `this` pointer; it must write `self.count`

**Why:** Under [expr.prim.this] and [class.mfct], `this` is not in scope as an expression inside an explicit object member function body. All member access must go explicitly through the named parameter `self` (`self.count`).

### Question 4 [tricky] ([dcl.fct], [expr.unary.op])

What is the exact type of `fn` when taking the address of explicit object member function `Counter::bump`?

```cpp
struct Counter {
    int value = 0;
    void bump(this Counter& self) { ++self.value; }
};
auto fn = &Counter::bump;
```

A. void (Counter::*)()
B. void (Counter::*)(Counter&)
C. void (*)(Counter&)
D. Ill-formed: you cannot take the address of an explicit object member function

**Answer (C):** void (*)(Counter&)

**Why:** Under [dcl.fct] and [expr.unary.op], an explicit object member function behaves like a non-member function for pointer formation: `&Counter::bump` yields a plain function pointer `void (*)(Counter&)`, not a pointer-to-member-function.

### Question 5 [standardese] ([dcl.fct], [class.mfct])

Which declaration of an explicit object member function is legal in C++23?

A. virtual void draw(this Shape& self);
B. void draw(this const Shape& self) noexcept;
C. void draw(this Shape& self) const;
D. static void draw(this Shape& self);

**Answer (B):** void draw(this const Shape& self) noexcept;

**Why:** Under [dcl.fct], a function declaration with an explicit object parameter cannot be `virtual`, `static`, cv-qualified (`const`/`volatile`), or ref-qualified (`&`/`&&`)—those properties belong on the explicit object parameter itself. Exception specifications like `noexcept` remain valid.

### Question 6 [standardese] ([expr.ref], [forward])

In `Box` below, why does `std::move(b).bad()` yield `std::string&` instead of `std::string&&`, whereas `std::move(b).good()` yields `std::string&&`?

```cpp
struct Box {
    std::string& item;
    template <class Self>
    decltype(auto) bad(this Self&& self) {
        return std::forward<Self>(self).item;
    }
    template <class Self>
    decltype(auto) good(this Self&& self) {
        return std::forward_like<Self>(self.item);
    }
};
```

A. std::forward<Self>(self) ignores template deduction when Self is an explicit object parameter
B. Member access on a template always decays rvalues to lvalues
C. std::forward_like forces a copy of item onto the stack
D. Under [expr.ref], accessing a reference member `E1.m` where `m` is `T&` produces an lvalue even when `E1` is an rvalue, whereas `std::forward_like<Self>` applies Self's value category onto `item`

**Answer (D):** Under [expr.ref], accessing a reference member `E1.m` where `m` is `T&` produces an lvalue even when `E1` is an rvalue, whereas `std::forward_like<Self>` applies Self's value category onto `item`

**Why:** By [expr.ref], member access on an rvalue yields an xvalue only for non-reference, non-static data members; when the member itself is an lvalue reference (`std::string&`), `E1.item` stays an lvalue. `std::forward_like<Self>(self.item)` transfers `Self`'s constness and value category onto `item` ([forward]).
