迭代基类和可变参数列表

时间:2017-11-09 16:35:01

标签: c++ templates variadic-templates

假设我有一个方法fun的结构如下。

template<class T, template <class> class ... base_t>
struct S : base_t<T> ... {
    template<class ... args_t>
    void fun(args_t& ... args) {
        //Here
    }
};

我想在//Here中做的是将第n个基数的operator()()调用的结果分配给第n个参数。这意味着如果我有两个这样的结构:

template<class>
struct D1 {
    double operator()() { return 4.2; }
};
template<class>
struct D2 {
    double operator()() { return 4.2; }
};
template<class>
struct I {
    int operator()() { return 42; }
};

然后此代码应打印4.2 4.2 42

S<double, D1, D2, I> s;
double a, b;
int c;
s.fun(a, b, c);
std::cout << a << ' ' << b << ' ' << c << std::endl;

1 个答案:

答案 0 :(得分:2)

在C ++ 17中,使用fold表达式:

template <typename ... base_t>
struct S : base_t ... {
    template<typename ... args_t>
    void fun(args_t& ... args) {
        (base_t::operator()(args), ...);
    }
};

Demo

相关问题