Adding functionality to classes with mixins
In the previous recipe, we learned about a pattern called the curiously recurring template pattern, or CRTP for short, and how it can be used to add common functionality to classes. This is not its only use; other use cases include limiting the number of times that a type can be instantiated and implementing the composite pattern. Related to this pattern, there is another one called mixins. Mixins are small classes that are designed to add functionality to other existing classes. You can probably find articles about this pattern claiming that it’s implemented using CRTP. That is not correct. Indeed, CRTP and mixins are similar patterns and both are used to add functionality to classes, but they don’t have the same structure. With CRTP, the base class adds functionality to the classes that derive from it. A mixin class adds functionality to a class that it derives from. Therefore, in a way, it is an upside-down CRTP. In this...