CRTP, a Slightly Unorthodox Form of Inheritance

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:

  1. a class inherits from a template base class;
  2. the derived class is passed as the template parameter of the base class.

The general form looks like this:

1
2
3
4
template <typename T>
class Base {...};

class Derived : public Base<Derived> {...};

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
2
3
4
5
6
7
8
9
10
11
12
template <class T> 
struct Base {
void interface() {
static_cast <T*>(this)->implementation();
}
};

struct Derived : Base<Derived> {
void implementation() {
std::cout << " Derived class " << std::endl;
}
};

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:

  1. A class template is a template; a class is a class. Here, Base is just the template.
  2. The base class is Base<Derived>, not Base.

Here are two questions worth thinking about:

  1. Does Base<Derived> actually implement implementation()? Would the following compile?
1
2
CRTPBase<CRTPDerived> base;
base.interface();
  1. What exactly does Derived inherit from Base<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, a Slightly Unorthodox Form of Inheritance: Virtual Function Cost (figure 1)

CRTP Cost (Inlining Disabled)

CRTP, a Slightly Unorthodox Form of Inheritance: CRTP Cost (Inlining Disabled) (figure 2)

CRTP Cost (Inlining Enabled)

CRTP, a Slightly Unorthodox Form of Inheritance: CRTP Cost (Inlining Enabled) (figure 3)

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
2
3
4
5
6
7
8
9
10
11
12
13
class Singleton
{
private:
Singleton() { };
~Singleton() { };
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
};

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename Derived>
class Singleton {
public :
template<typename ...Args>
static std::unique_ptr<Derived>& GetInstance(const Args& ...args) {
static std::unique_ptr<Derived> m_instance;
static std::once_flag m_flag;
std::call_once(m_flag, [](auto ...args) {
m_instance.reset(new Derived(args...));
}, args...);
return m_instance;
}
protected:
Singleton() = default;
~Singleton() = default;
private:
Singleton(Singleton&) = delete;
};

The derived class becomes the template parameter, and the singleton is constructed directly from the derived constructor. This uses:

  1. variadic templates, so any number of arguments can be passed;
  2. std::call_once and std::once_flag, which are very similar to dispatch_once and dispatch_once_t.

Any class that wants a singleton only needs to inherit from Singleton and pass itself as the template argument:

1
2
3
4
5
6
7
8
9
10
class TestService : public Singleton<TestService> {
public:
void doSomething() {
std::cout << "TestService doSomething" << std::endl;
}

private:
TestService() = default;
friend class Singleton<TestService>;
};
1
2
3
4
int main() {
TestService::GetInstance()->doSomething();
return 0;
}
  1. The subclass must make its constructor private.
  2. The subclass must declare Singleton<TestService> as a friend.

Simple Factory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
template <typename Derived, bool ThreadSafe = true>
class Factory {
public :
using WeakMap = WeakWrapper<std::map<std::string, std::unique_ptr<Derived>>>;

static StaticWrapper<WeakMap>& GetMap() {
static StaticWrapper<WeakMap> container;
return container;
}

static rwlock& GetLock() {
static rwlock *lock = new rwlock();
return *lock;
}

template <typename ...Args>
static std::unique_ptr<Derived>& GetInstance(const std::string& key, Args&& ...args) {
auto& container = GetMap();
auto& lock = GetLock();

if (ThreadSafe) lock.lock_shared();
auto safe_container = container.SafeGet();
auto map_ptr = safe_container.Lock();
auto& map = map_ptr->GetItem();
auto iter = map.find(key);
if (iter != map.end()) {
if (ThreadSafe) lock.unlock_shared();
return map[key];
}
if (ThreadSafe) lock.unlock_shared();
if (ThreadSafe) lock.lock();
map[key] = std::make_unique<Derived>(std::forward<Args>(args)...);
if (ThreadSafe) lock.unlock();
return map[key];
}

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
2
3
4
5
6
class SomeService : public  Factory <SomeService> {
public:
void doSomething();
};

SomeService::GetInstance(key, param)->doSomething();

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <typename ...Args>
static std::unique_ptr<Derived>& GetInstance(Args&& ...args) {
auto& container = GetMap();
auto& lock = GetLock();

auto key = DecayFirstParam(std::forward<Args>(args)...);

if (ThreadSafe) lock.lock_shared();
auto safe_container = container.SafeGet();
auto map_ptr = safe_container.Lock();
auto& map = map_ptr->GetItem();
auto iter = map.find(key);
if (iter != map.end()) {
if (ThreadSafe) lock.unlock_shared();
return map[key];
}
if (ThreadSafe) lock.unlock_shared();

if (ThreadSafe) lock.lock();
map[key] = std::make_unique<Derived>(std::forward<Args>(args)...);
if (ThreadSafe) lock.unlock();
return map[key];
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T, typename ...Args>
typename std::enable_if<std::is_same<typename std::decay<T>::type, std::shared_ptr<ModuleEnv>>::value, std::string>::type
DecayFirstParam(T&& t, Args&& ...arg) {
return t->GetModuleId();
}

template <typename T, typename ...Args>
typename std::enable_if<std::is_same<typename std::decay<T>::type, std::shared_ptr<Env>>::value, std::string>::type
DecayFirstParam(T&& t, Args&& ...arg) {
return t->GetIdentify();
}

template <typename T, typename ...Args>
typename std::enable_if<std::is_same<typename std::decay<T>::type, std::string>::value, std::string>::type
DecayFirstParam(T&& t, Args&& ...arg) {
std::string copy = t;
return copy;
}

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.

CRTP, a Slightly Unorthodox Form of Inheritance: Strategy Pattern (figure 4)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class IFlowControlStrategy {
public :
virtual ~IFlowControlStrategy() = default;
virtual long GetUploadMaxSize() = 0;
virtual long GetUploadInterval() = 0;
};

class NormalFlowControlStrategy : public IFlowControlStrategy {
public :
virtual long GetUploadMaxSize() override;
virtual long GetUploadInterval() override;
};


class LimitedFlowControlStrategy : public IFlowControlStrategy {
public :
virtual long GetUploadMaxSize() override;
virtual long GetUploadInterval() override;
};

With CRTP, it becomes:

CRTP, a Slightly Unorthodox Form of Inheritance: Strategy Pattern (figure 5)

  1. Define a CRTP base class BaseFlowControlStrategy.
  2. Define two derived strategies: NormalFlowControlStrategy and LimitedFlowControlStrategy.
  3. Expose GetUploadMaxSize and GetUploadInterval as template methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
template <class Derived>
class BaseFlowControlStrategy {
public :
long GetUploadMaxSize() {
return static_cast <Derived*>(this)->InternalGetUploadMaxSize();
}
long GetUploadInterval() {
return static_cast <Derived*>(this)->InternalGetUploadInterval();
}
};


class NormalFlowControlStrategy : public BaseFlowControlStrategy<NormalFlowControlStrategy> {
private:
friend class BaseFlowControlStrategy<NormalFlowControlStrategy>;
long InternalGetUploadMaxSize();
long InternalGetUploadInterval();
};

class LimitedFlowControlStrategy : public BaseFlowControlStrategy<LimitedFlowControlStrategy> {
private:
friend class BaseFlowControlStrategy<LimitedFlowControlStrategy>;
long InternalGetUploadMaxSize();
long InternalGetUploadInterval();
};

// API
template <class T>
long GetUploadMaxSize(BaseFlowControlStrategy<T>&& strategy) {
return strategy.GetUploadMaxSize();
}

template <class T>
long GetUploadInterval(BaseFlowControlStrategy<T>&& strategy) {
return strategy.GetUploadInterval();
}

Note the friend class here.

Calling code:

1
2
3
4
5
6
7
8
long  Context::GetUploadInterval() {
std::lock_guard<std::mutex> lock(m_strategy_mutex);
if (m_strategy_type == FlowControlStrategyTypeNormal) {
return GetUploadInterval(NormalFlowControlStrategy());
} else {
return GetUploadInterval(LimitedFlowControlStrategy());
}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Base class has a pure virtual function for cloning
class Shape {
public:
virtual ~Shape() {}
virtual Shape* Clone() const = 0;
};

// This CRTP class implements clone() for Derived
template <typename Derived>
class Shape_CRTP : public Shape {
public:
Shape* Clone() const override {
return new Derived(static_cast<Derived const&>(*this));
}
};

class Square : public Shape_CRTP<Square> {
public:
Square(Square& s);
// ...
};

class Circle : public Shape_CRTP<Circle> {
public:
Circle(Circle& c);
// ...
};

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct animal{
virtual int move()=0;
virtual ~animal() = default;
};

struct dog : public animal{
int move() override {
return 4;
}
void swim(){
std::cout<<"swim"<<std::endl;
}
};

struct bird : public animal{
int move() override {
return 2;
}
void fly(){
std::cout<<"fly"<<std::endl;
}
};

Now the question is: how do we call swim() and fly() through an animal object?

Downcasting

The most common approach is downcasting.

CRTP, a Slightly Unorthodox Form of Inheritance: Downcasting (figure 6)

1
2
3
4
5
6
7
void test(animal* anim) {
if(dynamic_cast<dog*>(anim)){
static_cast<dog*>(anim)->swim();
}else if(dynamic_cast<bird*>(anim)){
static_cast<bird*>(anim)->fly();
}
}

Many people have seen code like this, and many have written it, myself included. But the style is really not great:

  1. the if-else chain grows as requirements change;
  2. dynamic_cast is 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
struct visitor{
virtual void visit(dog*)=0;
virtual void visit(bird*)=0;
};

struct animal{
virtual int move()=0;
virtual void accept(visitor*) = 0;
virtual ~animal() = default;
};

struct dog : public animal{
int move() override {
return 4;
}

void accept(visitor* v){
v->visit(this);
}

void swim(){
std::cout<<"swim"<<std::endl;
}
};

struct bird : public animal{
int move() override {
return 2;
}

void accept(visitor* v){
v->visit(this);
}

void fly(){
std::cout<<"fly"<<std::endl;
}
};

struct visitor_impl : public visitor{
void visit(dog* d) override{
d->swim();
}

void visit(bird* b) override{
b->fly();
}
};

int main() {
visitor* v = new visitor_impl;

animal* a = new dog;
a->accept(v);

animal* b = new bird;
b->accept(v);
}

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:

  1. the first virtual call is animal::accept;
  2. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// crtp
template<typename T>
struct visitable : public animal{
void accept(visitor* v) override {
v->visit(static_cast<T*>(this));
}
};

struct dog : public visitable<dog>{
...
};

struct bird : public visitable<bird>{
...
};

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
template<typename T>
struct visitor {
virtual void visit(T*) = 0;
};


struct visitor_token{
virtual ~visitor_token() = default;
};

struct animal{
virtual int move()=0;
virtual void accept(visitor_token*) = 0;
virtual ~animal() = default;
};

template<typename T>
struct visitable : public animal {
void accept(visitor_token* v) override {
if(auto p = dynamic_cast<visitor<T>*>(v); p){
p->visit(static_cast<T*>(this));
}
}
};

struct dog : public visitable<dog>{
int move() override {
return 4;
}

void swim(){
std::cout<<"swim"<<std::endl;
}
};

struct bird : public visitable<bird>{
int move() override {
return 2;
}

void fly(){
std::cout<<"fly"<<std::endl;
}
};

struct fish : public visitable<fish> {
int move() override {
return 1;
}

void dive(){
std::cout<<"dive"<<std::endl;
}
};

template <class... T>
struct MultipleVisitor : public visitor_token, public visitor<T>... {
};

using MyVisitor = MultipleVisitor<dog, bird>;
using MyVisitor1 = MultipleVisitor<fish>;

struct visitor_impl : public MyVisitor{
void visit(dog* d) override{
d->swim();
}
void visit(bird* b) override{
b->fly();
}
};

struct visitor_impl1 : public MyVisitor1{
void visit(fish* f) override{
f->dive();
}
};

int main()
{
visitor_token* v = new visitor_impl;

animal* a = new dog;
a->accept(v);

animal* b = new bird;
b->accept(v);

visitor_token* v1 = new visitor_impl1;

animal* c = new fish;
c->accept(v1);
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 1. Specialize the two interface classes
template<>
struct visitor<dog> {
virtual void visit(dog*) = 0;
};
template<>
struct visitor<bird> {
virtual void visit(bird*) = 0;
};

// 2. Expand inheritance
struct MyVisitor : public visitor_token, public visitor<dog>, public visitor<bird> {
virtual void visit(dog*) = 0;
virtual void visit(bird*) = 0;
};

One line of code replaces about 15 lines. That is the charm of templates.

Questions

Do you see any problems so far?

  1. The final solution does not fully eliminate dynamic_cast. You can still see it inside accept:
1
2
3
4
5
6
7
8
template<typename T>
struct visitable : public animal {
void accept(visitor_token* v) override {
if(auto p = dynamic_cast<visitor<T>*>(v); p){
p->visit(static_cast<T*>(this));
}
}
};
  1. The code still uses a vtable and vptr. You can look at the vtable for visitor_impl:

CRTP, a Slightly Unorthodox Form of Inheritance: Questions (figure 7)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<class _Tp>
class enable_shared_from_this
{
mutable weak_ptr<_Tp> __weak_this_;
protected:
enable_shared_from_this() _NOEXCEPT {}
enable_shared_from_this(enable_shared_from_this const&) _NOEXCEPT {}
enable_shared_from_this& operator=(enable_shared_from_this const&) _NOEXCEPT
{return *this;}
~enable_shared_from_this() {}
public :
shared_ptr<_Tp> shared_from_this()
{return shared_ptr<_Tp>(__weak_this_);}
shared_ptr<_Tp const> shared_from_this() const
{return shared_ptr<const _Tp>(__weak_this_);}

template <class _Up> friend class shared_ptr;
};

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
2
3
4
5
6
7
8
9
10
11
12
13
// correct
struct Good: std::enable_shared_from_this<Good> {
std::shared_ptr<Good> getptr() {
return shared_from_this();
}
};

// wrong
struct Bad {
std::shared_ptr<Bad> getptr() {
return std::shared_ptr<Bad>(this);
}
};

ClickHouse

https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/IAggregateFunction.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class IAggregateFunction : public std::enable_shared_from_this<IAggregateFunction>
{
public:
IAggregateFunction(const DataTypes & argument_types_, const Array & parameters_)
: argument_types(argument_types_), parameters(parameters_) {}

/// Get main function name.
virtual String getName() const = 0;

/// Get the result type.
virtual DataTypePtr getReturnType() const = 0;

/// Get the data type of internal state. By default it is AggregateFunction(name(params), argument_types...).
virtual DataTypePtr getStateType() const;

// ...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// Implement method to obtain an address of 'add' function.
template <typename Derived>
class IAggregateFunctionHelper : public IAggregateFunction
{
private:
static void addFree(const IAggregateFunction * that, AggregateDataPtr place, const IColumn ** columns, size_t row_num, Arena * arena)
{
static_cast<const Derived &>(*that).add(place, columns, row_num, arena);
}

public:
IAggregateFunctionHelper(const DataTypes & argument_types_, const Array & parameters_)
: IAggregateFunction(argument_types_, parameters_) {}

AddFunc getAddressOfAddFunction() const override { return &addFree; }

// ...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// Implements several methods for manipulation with data. T - type of structure with data for aggregation.
template <typename T, typename Derived>
class IAggregateFunctionDataHelper : public IAggregateFunctionHelper<Derived>
{
protected:
using Data = T;

static Data & data(AggregateDataPtr __restrict place) { return *reinterpret_cast<Data *>(place); }
static const Data & data(ConstAggregateDataPtr __restrict place) { return *reinterpret_cast<const Data *>(place); }

public:
// Derived class can `override` this to flag that DateTime64 is not supported.
static constexpr bool DateTime64Supported = true;

IAggregateFunctionDataHelper(const DataTypes & argument_types_, const Array & parameters_)
: IAggregateFunctionHelper<Derived>(argument_types_, parameters_) {}
// ...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// Simply count number of calls.
class AggregateFunctionCount final : public IAggregateFunctionDataHelper<AggregateFunctionCountData, AggregateFunctionCount>
{
public:
explicit AggregateFunctionCount(const DataTypes & argument_types_) : IAggregateFunctionDataHelper(argument_types_, {}) {}

String getName() const override { return "count"; }

DataTypePtr getReturnType() const override
{
return std::make_shared<DataTypeUInt64>();
}
// ...
};

Summary

This article covered:

  1. the CRTP concept;
  2. performance comparison with virtual functions;
  3. several design-pattern use cases;
  4. 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
2
3
4
5
template<typename... Mixins>
class MixinClass : public Mixins... {
public:
MixinClass() : 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Point {
double x;
double y;
};

struct LabelPoint : Point {
std::string label;
};

struct ColorPoint : Point {
unsigned char red;
unsigned green;
unsigned blue;
};

struct LabelColorPoint : virtual LabelPoint, virtual ColorPoint {

};

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <typename... Mixins>
struct Point : public Mixins... {
double x, y;
Point() : Mixins()..., x(0.0), y(0.0) {}
Point(double x, double y) : Mixins()..., x(x), y(y) {}
};

struct Label {
Label() : label("") {}
std::string label;
};

struct Color {
unsigned char red;
unsigned green;
unsigned blue;
};

using LabelColorPoint = Point<Label, Color>;
1
2
3
4
5
int main() {
LabelColorPoint lcp;
std::cout << lcp.x << lcp.label << lcp.red << std::endl;
return 0;
}

Mixin is called the ghost sibling of CRTP mainly because the inheritance direction looks opposite on the surface:

  1. CRTP passes the derived class as a template parameter, and the base template calls derived-class functionality;
  2. Mixin passes the base classes as template parameters, and the derived template calls base-class functionality through combined inheritance.

References

  1. Curiously recurring template pattern - Wikipedia
  2. The cost of dynamic virtual calls vs. static CRTP dispatch in C++
  3. C++ universal references and perfect forwarding
  4. WTL / ATL CWindowImpl Composition Notebook
  5. C++ Design Pattern: Policy-Based Class
  6. Modern C++ design-pattern references
-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:CRTP, a Slightly Unorthodox Form of Inheritance

Author:lingyun

Published:2022-06-24 01:08

Updated:2026-10-07 00:00

Original link:https://tsuijunxi.github.io/en/2022/06/24/crtp-a-slightly-unorthodox-inheritance/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.