Search code examples
c++scalac++11mixins

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


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

Solution

  • 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(); 
    }