0Pricing
C++ Academy · Lesson

Mixins with CRTP

Compose behavior at compile time.

What Is a Mixin?

A mixin is a small reusable unit of behavior you compose into a class. With CRTP, mixins add functionality at compile time while still calling into the host class.

A Simple Mixin

This mixin adds a print_twice method that relies on the host providing value().

#include <iostream>

template <typename T>
struct PrintTwice {
    void print_twice() const {
        auto v = static_cast<const T*>(this)->value();
        std::cout << v << " " << v << "\n";
    }
};

struct Box : PrintTwice<Box> {
    int value() const { return 7; }
};

int main() {
    Box{}.print_twice();
    return 0;
}

All lessons in this course

  1. The CRTP Idiom
  2. Static Polymorphism
  3. Mixins with CRTP
  4. When to Use CRTP
← Back to C++ Academy