Solving the mixin constructor problem in C++ using variadic templates

Eit*_*tan 5 c++ templates variadic mixins boost-tuples

我最近解决了构造函数问题,其中相互装饰的各种mixins类(和最顶层的宿主类)具有不同的构造函数签名。为了在产生的修饰类中维护单个构造函数,并且不添加init函数,我找到了以下解决方案。它对mixin类的唯一限制是,如果其构造函数使用多个参数,则应将它们全部封装在一个元组中。(使用g ++编译此代码需要-std = c ++ 0x标志)

#include <boost/tuple/tuple.hpp>

// Base class for all mixins
struct Host {
    float f_;
    int i_;

    Host(float f, int i) : f_(f), i_(i) {}
};

// First mixin--constructs with 1 parameter
template <class B>
struct M1 : public B {
    char c_;

    template <class... A>
    M1(char c, const A&... a) : B(a...), c_(c) {}
};

// Second mixin--constructs with 3 parameters
template <class B>
struct M2 : public B {
    double d_;
    short s_;
    const char* p_;

    template <class... A>
    M2(boost::tuple<const char*, double, short> t, const A&... a)
    : B(a...), p_(t.get<0>()), d_(t.get<1>()), s_(t.get<2>()) {}
};


int main() {
    // ctor parameters go in this order, from most derived to base:
    M2<M1<Host>> tst(boost::make_tuple("test", 46.1, (short)-1), (char)5, 4.2f, 2);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:
1)是否有更好,更优雅的方式使用C ++ 0X解决此问题?
2)具体来说,元组真的必要吗?

Geo*_*che 4

如果您有多个具有不同混合数量的构造函数(因此存在歧义),那么您只需要像元组这样的东西。

如果没有,你可以像往常一样处理 mixin 的参数:

template <class... A>
M2(const char* p, double d, short s, const A&... a)
  : B(a...), p_(p), d_(d), s_(s) {}
Run Code Online (Sandbox Code Playgroud)