所以我有一个具有不同参数类型的可变参数函数;我想将每个参数传递给另一个函数,它是一个 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);
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用,
template <int I, class... Ts>
decltype(auto) get(Ts &&... ts)
{
return std::get<I>(std::forward_as_tuple(ts...));
}
Run Code Online (Sandbox Code Playgroud)
但由于 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), ...);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |