Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 312
Roay Spol Avatar asked Jul 13 '13 08:07

Roay Spol


People also ask

Is it possible to build objects out of mixins at run-time?

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.

What is the use of mixin class?

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.

What is a mixin in Java?

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.

Why don't mixins exist in Scala?

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.


1 Answers

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(); 
}
like image 113
emesx Avatar answered Nov 12 '22 16:11

emesx