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]):
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:
- Wrong template argument copy-paste: Writing
struct B : CounterMixin<A>instead ofCounterMixin<B>causes undefined behavior whenCounterMixin<A>casts*thistoA&! Guard against this by makingCounterMixin's constructorprivateand declaringfriend Derived;. - Incomplete
Derivedduring instantiation: Inside the class body ofCounterMixin<Metric>,Metricis still an incomplete type whileCounterMixin<Metric>is being instantiated asMetric's base. Member function bodies may referenceDerived(since function bodies are instantiated lazily upon use), whereas non-static data members or signature return types liketypename Derived::value_typewill fail becauseDerivedis not complete yet. - Dependent base name lookup (
[temp.dep]): When a class templateChild<T>inherits from a dependent baseBase<T>, two-phase lookup does not examineBase<T>during unqualified lookup. Access base members viathis->memberorBase<T>::member.
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.
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:
#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.
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:
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:
Printableis an ordinary non-template class;Badgesimply inheritsPrintable, eliminatingBase<WrongType>bugs, dependent base lookup issues, andstatic_cast<Derived&>(*this)boilerplate. - Recursive lambdas: Writing
(this auto&& self, int n)inside a lambda bindsselfdirectly to the closure object, giving zero-overhead self-recursion withoutstd::functiontype erasure or passing the lambda to itself. - Pass-by-value
this: Small scalar-like types can declarevoid tick(this Counter copy)to receivethisin 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), callingself.emit()respects normal member access rules—soBadge::emit()must bepublic(orPrintabledeclared afriend), whereas private helpers onPrintableitself require care becauseselfcarries static typeBadge, notPrintable. - 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-valuethisremoves aliasing concerns on immutable small handles.
What to remember
- Classic CRTP achieves zero-overhead static polymorphism via
Base<Derived>andstatic_cast<Derived&>(*this), but breaks ifBaseinvokesDerivedduring construction/destruction or relies on incomplete members ofDerived. - Always guard classic CRTP constructors (
private+friend Derived) to prevent inheritingBase<WrongType>, and qualify dependent base members withthis->. - 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, forbidvirtual/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 fromthis Self&& selfso reference members still respect the owner's constness and rvalue-ness.