Mixins For Cee Plus Plus

Here are some examples of Mix Ins for Cee Plus Plus


In the context of C++ [Cee Plus Plus] the term mixin is usually used to match Bjarne Stroustrup's definition:

A class that provides some - but not all - of the implementation for a virtual base class is often called a "mixin".

You can for example have a virtual abstract base class that defines the interfaces for the import and export of values and a flock of derived classes that implement different means to either export or import, but not both. Then you can combine these second-layer classes to form different concrete classes.


I believe that it's possible to Mix In from above (parent classes) or Mix In from below (Abstract Subclasses). The above example shows an example of Mix In from the parent classes through Multiple Inheritance. For Cee Plus Plus, Abstract Subclasses written by Using Templates.


Examples for Mix In through Abstract Subclass

The following code implements the Singleton Pattern

template<class S''''''ingletonClass>

class Singleton :
public SingletonClass

{ public: /** Singleton creation function */ static Singleton & instance() { if(_instance.get() == NULL) { _instance = auto_ptr<Singleton<S''''''ingletonClass> >(new Singleton); assert(_instance.get() != NULL); } return *_instance; }

protected: /** Singleton instance holder */ static auto_ptr<Singleton<S''''''ingletonClass> > _instance; };

/** static instance definition */

template<class S''''''ingletonClass> auto_ptr<Singleton<S''''''ingletonClass> > Singleton<S''''''ingletonClass>::_instance;

If we have a class called MyClass:

class M''''''yClass { public: virtual void bar(); virtual ~M''''''yClass(); protected: M''''''yClass(); };

The constructor can either be public or protected depending on the need. A protected constructor can ensure that the class will only be possible to be constructed by subclasses in this case the Singleton Mix In.

The Mix In can be used like:

void foo() { Singleton<M''''''yClass>::instance().bar(); }

or

class SingletonMyClass :
public SingletonyClass>

{ };

void foo() { S''''''ingletonMyClass::instance().bar(); }

The STL's auto_ptr is used to ensure proper destruction. In this example, the abstract method this Mix In requires from the parent class is the default constructor. The disadvantage is that it is harder to pass parameters through constructor, but the advantage is Once And Only Once because any class can be a singleton by mixing in the Abstract Subclass without rewriting the same code.

See original on c2.com