Home

CRTP

CRTP, the Curiously Recurring Template Pattern, is a C++ technique in which a class X derives from a template base class instantiated with X itself. A typical form is: template<class Derived> struct Base { void interface() { static_cast<Derived*>(this)->implementation(); } }; struct Derived : Base<Derived> { void implementation(); }; The base provides common behavior while the derived class supplies the concrete implementation. This arrangement enables static polymorphism, allowing code to call derived methods without virtual dispatch and with potential inlining.

Advantages include zero runtime overhead from virtual functions, opportunities for aggressive optimization, and the ability to

Limitations include the absence of dynamic polymorphism; a base class object does not behave polymorphically through

Common uses include policy-based design, static interfaces, and chainable APIs. CRTP is popular in performance-critical libraries

implement
mixins
or
fluent
interfaces.
CRTP
also
enables
polymorphic-like
interfaces
at
compile
time
and
can
support
SFINAE-based
checks
to
select
overloads
depending
on
the
presence
of
methods
in
the
derived
class.
a
derived
type
at
runtime.
It
can
increase
template
complexity,
lead
to
opaque
compiler
error
messages,
and
complicate
maintenance.
It
also
ties
the
base
to
a
particular
derived
pattern,
making
refactoring
risky
if
the
hierarchy
changes.
Correct
use
often
requires
careful
design
and
documentation
to
avoid
brittle
interfaces.
that
favor
compile-time
polymorphism
and
in
scenarios
where
virtual
dispatch
would
be
too
costly
or
insufficiently
flexible.