调用函数,其中参数的数量由模板参数值定义

时间:2018-06-18 10:13:50

标签: c++14 variadic-templates

我需要这样做:

#include <utility>
double& f(int i); // gets reference to an element in an array to be modified
void g(double& a); // uses references to modify the arguments
void g(double& a, double& b);
// other functions g with different amount of double& parameters

template<int N> void callG()
{
// should call g with N parameters: g(f(0), f(1),      , f(n));
}

int main()
{
  callG<1>; // calls g(f(0));
  callG<2>; // calls g(f(0), f(1));
  return 0;
}

我试过了 g(f(std::make_index_sequence<N>)...);

和一些类似的变体,但得到

  

期望'('用于函数式转换或类型构造

如何从integer_sequence创建参数包?还有其他解决方案吗?

2 个答案:

答案 0 :(得分:2)

当您拥有时,只能使用image.php包扩展运算符。 ...不是一个包。添加一个间接层:

std::make_index_sequence<N>

live example on wandbox.org

答案 1 :(得分:1)

#include <utility>

double& f(int i);
void g(double& a);
void g(double& a, double& b);

template <size_t... Ints>
void callG(std::integer_sequence<size_t, Ints...>) {
    g(f(Ints)...);
}

template <int N>
void callG() {
    callG(std::make_index_sequence<N>());
}

int main() {
    callG<1>();
    callG<2>();
    return 0;
}
相关问题