W
Werner
Hi All,
I've recently used mixins (without the courtesy of
compilers supporting variadic templates) and were
irritated by the fact that one had to always implement
many constructors (one per base):
Definition of Mixin: courtesy of http://www.drdobbs.com/cpp/184404445
A mixin is a fragment of a class that is intended to be composed with other classes or mixins...
For the problem I've come up with this solution (amongst others).
What do you think?
//////////////////////////////////////
#include <iostream>
struct Base
{
Base();
Base( int i, int j ){}
virtual void foo()
{
std::cout << "Base::foo()" << std::endl;
}
};
template <class BaseT>
struct Mixin : virtual BaseT
{
typedef BaseT base_type;
//Problem
//-Which constructor...? Always default... Generic!
//Adds foo to any Base...
virtual void foo()
{
std::cout << "Derived::foo()" << std::endl;
}
};
//Solution? Something that calls base
// constructor directly-always...
template <class MixinT>
struct GenMixin :
virtual MixinT::base_type,
MixinT
{
typedef typename MixinT::base_type base_type;
GenMixin()
{
}
template <class A0>
GenMixin( A0 a0 )
: base_type( a0 )
//Mixin always has default only...
{
}
template <class A0, class A1>
GenMixin( A0 a0, A1 a1 )
: base_type( a0, a1 )
//Mixin always has default only...
{
}
};
typedef GenMixin<Mixin<Base> > MyMixin;
int main()
{
MyMixin( 1, 2 ).foo();
}
I've recently used mixins (without the courtesy of
compilers supporting variadic templates) and were
irritated by the fact that one had to always implement
many constructors (one per base):
Definition of Mixin: courtesy of http://www.drdobbs.com/cpp/184404445
A mixin is a fragment of a class that is intended to be composed with other classes or mixins...
For the problem I've come up with this solution (amongst others).
What do you think?
//////////////////////////////////////
#include <iostream>
struct Base
{
Base();
Base( int i, int j ){}
virtual void foo()
{
std::cout << "Base::foo()" << std::endl;
}
};
template <class BaseT>
struct Mixin : virtual BaseT
{
typedef BaseT base_type;
//Problem
//-Which constructor...? Always default... Generic!
//Adds foo to any Base...
virtual void foo()
{
std::cout << "Derived::foo()" << std::endl;
}
};
//Solution? Something that calls base
// constructor directly-always...
template <class MixinT>
struct GenMixin :
virtual MixinT::base_type,
MixinT
{
typedef typename MixinT::base_type base_type;
GenMixin()
{
}
template <class A0>
GenMixin( A0 a0 )
: base_type( a0 )
//Mixin always has default only...
{
}
template <class A0, class A1>
GenMixin( A0 a0, A1 a1 )
: base_type( a0, a1 )
//Mixin always has default only...
{
}
};
typedef GenMixin<Mixin<Base> > MyMixin;
int main()
{
MyMixin( 1, 2 ).foo();
}