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
- The CRTP Idiom
- Static Polymorphism
- Mixins with CRTP
- When to Use CRTP