繁体   English   中英

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), ...);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM