Roay Spol Roay Spol - 1 year ago 87
Scala Question

Is it posible to create per-instance mixins in C++11?

Is it posible 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

Answer Source

If these were your existing classes:

class Person
    Person(const string& name): name_(name) {}
    void name() { cout << "name: " << name_ << endl; }

    string name_;

class Singer
    Singer(const string& song, int year): song_(song), year_(year) {}
    void song() { cout << "song: " << song_ << ", " << year_ << endl; }

    string song_;
    int year_;

Then you could play around with this concept in C++11

template<typename... Mixins>
class Mixer: public Mixins...
    Mixer(const Mixins&... mixins): Mixins(mixins)... {}

to use it like this:

int main() {    
    Mixer<Person,Singer> dylan{{"Dylan"} , {"Like a Rolling Stone", 1965}};;; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download