使用可变参数模板解决C ++中的mixin构造函数问题

时间:2010-07-31 15:48:12

标签: c++ templates mixins variadic boost-tuples

我最近解决了the constructor problem,其中相互装饰的各种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;
}

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

2 个答案:

答案 0 :(得分:4)

如果你有多个具有不同arity的构造函数(因此含糊不清),你只需要像元组这样的东西。

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

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

答案 1 :(得分:0)

你可以构造基础结构并将其作为M1和M2的构造函数参数传递,这样它们就可以调用b的复制构造函数:

M2(const B &b, ....) : B(b), ....

你真的确定需要继承吗?构图更优雅,更易于维护。