CRTP (Mixins)

Learn how CRTP can be used to implement mixins in C++.

Mixins

Mixins are a class with methods that can be used by classes even if they’re not derived from them. It’s a popular idea when designing classes to mix in new code. Therefore, it’s a technique often used in Python to change the behavior of a class by using multiple inheritances. In contrast to C++, it’s legal in Python to have more than one definition of a method in a class hierarchy. Python simply uses the method that’s first in the Method Resolution Order (MRO).

Example

We can implement mixins in C++ by using CRTP. A prominent example is the std::enable_shared_from_this class.

Get hands-on with 1200+ tech skills courses.