Is it possible to create mixins in C++ (C++11) - I want to create behavior per instance, not per class.
In Scala I'd do this with anonymous classes
val dylan = new Person with Singer
Besides the static approach suggested by emesx, I'm familiar with at least one C++ library that allows you to build objects out of mixins at run-time.
Mixin class does not necessarily have to be the parent class of all those other classes. That means, Mixin can be referred to as “included” instead of “inherited”. Mixin brings in the code reusability and can be used to avoid the classic diamond of death problem because of inheritance ambiguity that can be caused by multiple inheritance.
A mixin is a class that provides a certain functionality to be inherited by a subclass, but is not meant to stand alone. Inheriting from a mixin is not a form of specialization but is rather a means to collect functionality. A class may inherit most or all of its functionality by inheriting from one or more mixins through multiple inheritance.
Perhaps because Scala is a statically typed and compile-time bound language (for the most part), and so it has some of the hurdles with implementing mixins that C# would face. In Scala the feature is called "traits" and traits can be applied to both classes and instances during construction.
If these were your existing classes:
class Person
{
public:
Person(const string& name): name_(name) {}
void name() { cout << "name: " << name_ << endl; }
protected:
string name_;
};
class Singer
{
public:
Singer(const string& song, int year): song_(song), year_(year) {}
void song() { cout << "song: " << song_ << ", " << year_ << endl; }
protected:
string song_;
int year_;
};
Then you could play around with this concept in C++11
template<typename... Mixins>
class Mixer: public Mixins...
{
public:
Mixer(const Mixins&... mixins): Mixins(mixins)... {}
};
to use it like this:
int main() {
Mixer<Person,Singer> dylan{{"Dylan"} , {"Like a Rolling Stone", 1965}};
dylan.name();
dylan.song();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With