C++ 元编程拆分函数参数并将它们一个接一个地传递给另一个函数

C++ metaprogramming to split the function arguments and pass them one by one to another function

所以我有一个具有不同参数类型的可变参数函数;我想将每个参数传递给另一个 C 函数函数。举个例子; 对于有两个参数的情况;

void function(int *a, double *b) needs to call
{
  bindToFunc(0, a);
  bindToFunc(1, b);
}

void function(int *a, double *b, float *c) needs to call
{
  bindToFunc(0, a);
  bindToFunc(1, b);
  bindToFunc(2, c);
}

template<typename... T>
void function(T ...)
{
  // has to have
  // 
  // bindToFunc(0, T0) ....
  // bindToFunc(n-1, Tn-1);
}

我试过使用,

template <int I, class... Ts> 
decltype(auto) get(Ts &&... ts) 
{
  return std::get<I>(std::forward_as_tuple(ts...));
}

但由于 I 是模板参数,它是一个编译时变量,因此我们不能在 for 循环中使用它。

使用 C++17 和 fold expression,您可以:

template<typename... Ts>
void function(Ts... args)
{
    [[maybe_unused]] int i = 0; // Not used for empty pack.
    (bindToFunc(i++, args), ...);
}