Background
While writing some C++ code recently, I ran into a few repetitive patterns. While thinking about how templates could help, I remembered CRTP, a rather unusual form of inheritance.
What Is CRTP?
CRTP stands for Curiously Recurring Template Pattern. It is a common idiom in C++ template programming. It was proposed by James Coplien in 1995 and has two defining traits:
- a class inherits from a template base class;
- the derived class is passed as the template parameter of the base class.
The general form looks like this:
1 | template <typename T> |
Few languages express inheritance in quite this self-referential way, which is part of what makes CRTP look so strange at first.
So why does this work? And why would anyone design it like this?
Here is a small example:
1 | template <class T> |
At this point, many people start wondering about time travel, because
the code looks quite strange. Derived seems to inherit from
itself, and it is used before it is fully declared.
In practice, a base-class template can use the fact that a member function may be declared early, but is only instantiated when the derived class actually uses it. That allows the base template to call methods on the derived type.
In the example above, Base<Derived>::interface()
is declared before Derived, but it will not be instantiated
until it is used. By then, Derived::implementation() is
already visible to the compiler.
Without virtual functions, a base class always calls its own implementation. If a derived class calls an inherited function, and that function calls another member function, the derived override is never selected.
With CRTP, however, the base class can route the call to the derived class at compile time, effectively simulating virtual dispatch without the runtime cost of a vtable lookup. This is usually called static polymorphism.
There are two things to keep in mind:
- A class template is a template; a class is a class. Here,
Baseis just the template. - The base class is
Base<Derived>, notBase.
Here are two questions worth thinking about:
- Does
Base<Derived>actually implementimplementation()? Would the following compile?
1 | CRTPBase<CRTPDerived> base; |
- What exactly does
Derivedinherit fromBase<Derived>, or what promise is it following?
How Fast Is CRTP?
Environment: x86-64 clang 14.0.0 -std=c++14
Virtual Function Cost

CRTP Cost (Inlining Disabled)

CRTP Cost (Inlining Enabled)

Comparison
| type | virtual function | CRTP (no inline) | CRTP (inline) |
|---|---|---|---|
| time | 28ms | 18ms | 1ms |
| object size | 16B | 8B | 8B |
In this demo, CRTP is faster when inlining is enabled, and the object is smaller because it does not need a vptr. For performance-sensitive code, it is worth considering. Of course, this is only a simple benchmark; a real comparison would require proper benchmarking.
What Happens When CRTP Meets Design Patterns?
What can CRTP be used for? How should it be applied? Let us start with a few classic design patterns. When CRTP meets them, things get interesting.
Singleton
How is a singleton usually written in C++?
1 | class Singleton |
C++11 guarantees thread-safe initialization of local statics. In
C++11, Effective C++ recommends the elegant Meyers’
Singleton, which creates the instance only on first call to
getInstance(). Before C++11, locking was still needed.
What if another class also needs a singleton? The brute-force solution is to copy the code. But with CRTP:
1 | template <typename Derived> |
The derived class becomes the template parameter, and the singleton is constructed directly from the derived constructor. This uses:
- variadic templates, so any number of arguments can be passed;
std::call_onceandstd::once_flag, which are very similar todispatch_onceanddispatch_once_t.
Any class that wants a singleton only needs to inherit from
Singleton and pass itself as the template argument:
1 | class TestService : public Singleton<TestService> { |
1 | int main() { |
- The subclass must make its constructor private.
- The subclass must declare
Singleton<TestService>as a friend.
Simple Factory
1 | template <typename Derived, bool ThreadSafe = true> |
A class can simply inherit from Factory and pass itself
as the template parameter. Since the factory stores objects as key-value
pairs, the caller also has to pass a key.
1 | class SomeService : public Factory <SomeService> { |
That call site is awkward because you need to keep passing a key that you do not really want. So let us improve it:
1 | template <typename ...Args> |
The core idea is to extract the first argument and derive the final
key from its type. Here DecayFirstParam extracts the first
argument, which is a bit like type extraction. Because the first
parameter type is not fixed, std::enable_if is used to
overload the method for the concrete types used in the project:
ModuleEnv, Env, and
std::string.
1 | template <typename T, typename ...Args> |
This also uses universal references and perfect forwarding, but that is not the focus here.
Strategy Pattern
Here is a flow-control example. Suppose there are two modes: normal mode and limited mode.

1 | class IFlowControlStrategy { |
With CRTP, it becomes:

- Define a CRTP base class
BaseFlowControlStrategy. - Define two derived strategies:
NormalFlowControlStrategyandLimitedFlowControlStrategy. - Expose
GetUploadMaxSizeandGetUploadIntervalas template methods.
1 | template <class Derived> |
Note the
friend classhere.
Calling code:
1 | long Context::GetUploadInterval() { |
The public API is a template method, which means it does not really fit the traditional OOP style.
Another name for this pattern is Policy-Based Class Design.
Clone Pattern
When you want to get a copy of an object through a base pointer, the
usual approach is to add a virtual Clone method. With CRTP,
the function does not need to be repeated in every derived class, as
long as the derived class is copy-constructible.
1 | // Base class has a pure virtual function for cloning |
Visitor Pattern
The visitor pattern itself is already fairly complex, and mixing it with CRTP makes things more interesting. I will use an example from the modern C++ design-pattern series.
Suppose there is an animal hierarchy: dog and
bird derive from animal, and the base class
has a pure virtual move() method. As requirements evolve,
we add swim() to dog and fly() to
bird. Since dogs cannot fly and birds cannot swim, those
methods do not belong in the base animal class.
1 | struct animal{ |
Now the question is: how do we call swim() and
fly() through an animal object?
Downcasting
The most common approach is downcasting.

1 | void test(animal* anim) { |
Many people have seen code like this, and many have written it, myself included. But the style is really not great:
- the
if-elsechain grows as requirements change; dynamic_castis inefficient and should be avoided when possible.
Visitor to the Rescue
This is where the visitor pattern comes in: it adds new behaviors
without modifying the visited object, and it removes the need for
dynamic_cast.
1 | struct visitor{ |
This is the classic visitor pattern. For the animal
hierarchy, the way you visit an animal can be extended
freely through a visitor, and the animal hierarchy itself
is not aware of it. In other words, you can add new behaviors without
modifying the visited object. That is a great property.
This is also the classic double dispatch visitor pattern. Double dispatch means two dispatches, i.e. two virtual function calls:
- the first virtual call is
animal::accept; - the second virtual call is
visitor::visit.
CRTP steps in
Do you notice one annoying method? Yes, accept. Both
dog and bird implement it, and the code is
identical. Following the clone-pattern trick from earlier, we can
eliminate this duplication by moving accept into a
visitable class derived from animal. From now
on, the derived classes no longer inherit animal directly;
they inherit visitable.
1 | // crtp |
The derived classes immediately look much cleaner, right?
And now the magic
If we add another subclass fish, then the
visitor base class needs a new virtual function, and all
previous derived classes need to change. That makes this code unstable
and violates the open-closed principle. The reason is that
animal depends on visitor, and
visitor depends on concrete animal types.
SOLID reminds us to depend on abstractions rather than concrete
classes.
So we can make visitor a template class, so
animal depends on a generic type instead of a concrete one.
Because templates are contagious, and we do not want to template-ify
animal as well, we introduce a visitor_token
base class. It is just a helper base class with nothing but a default
virtual destructor, but that is enough.
1 | template<typename T> |
At this point, both visitor and animal
depend only on abstractions, which achieves decoupling.
The biggest trick here comes from MultipleVisitor, which
uses using-declaration
to automatically generate a visitor inheritance hierarchy, instead of
defining each derived visitor class by hand. This simplifies the code
and makes it easy to define new visitor hierarchies: just add a new
type.
This part may feel a little abstract, so let us expand the equivalent
code for
using MyVisitor = MultipleVisitor<dog, bird>:
1 | // 1. Specialize the two interface classes |
One line of code replaces about 15 lines. That is the charm of templates.
Questions
Do you see any problems so far?
- The final solution does not fully eliminate
dynamic_cast. You can still see it insideaccept:
1 | template<typename T> |
- The code still uses a vtable and vptr. You can look at the vtable
for
visitor_impl:

So the elegant-looking final code is still somewhat away from the original goal. But you usually have to make trade-offs, and these trade-offs are worth it.
Real-World CRTP Usage
std::enable_shared_from_this
1 | template<class _Tp> |
When using smart pointers, if you want a smart pointer to
this, the correct way is to inherit from
std::enable_shared_from_this and pass yourself as the
template parameter.
1 | // correct |
ClickHouse
https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/IAggregateFunction.h
1 | class IAggregateFunction : public std::enable_shared_from_this<IAggregateFunction> |
1 | /// Implement method to obtain an address of 'add' function. |
1 | /// Implements several methods for manipulation with data. T - type of structure with data for aggregation. |
1 | /// Simply count number of calls. |
Summary
This article covered:
- the CRTP concept;
- performance comparison with virtual functions;
- several design-pattern use cases;
- practical examples.
The strengths of CRTP are:
- high performance;
- code reuse;
- easier extension than single inheritance in some cases.
The weaknesses of CRTP are:
- it is hard to understand;
- it does not fit traditional OOP very naturally;
- template use can spread quickly through the codebase.
Postscript: The Ghost Sibling of CRTP
CRTP dates back to 1995, but it has a less famous relative worth revisiting: Mixin. A mixin is a C++ template technique that combines independent feature classes through inheritance. The basic idea is to treat template parameters as base classes:
1 | template<typename... Mixins> |
Take Point as an example. Traditionally, if we want to
extend it, we would derive LabelPoint,
ColorPoint, LabelColorPoint, and so on. You
can see that LabelColorPoint uses diamond
inheritance, which requires virtual
inheritance:
1 | struct Point { |
The mixin approach instead defines Label and
Color as separate classes, and then combines them into
LabelColorPoint by composition-like inheritance, like
building blocks:
1 | template <typename... Mixins> |
1 | int main() { |
Mixin is called the ghost sibling of CRTP mainly because the inheritance direction looks opposite on the surface:
- CRTP passes the derived class as a template parameter, and the base template calls derived-class functionality;
- Mixin passes the base classes as template parameters, and the derived template calls base-class functionality through combined inheritance.