gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:09:03 25 4
gpt4 key购买 nike

所以我有一个具有不同参数类型的可变参数函数;我想将每个参数传递给另一个 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), ...);
}

关于C++ 元编程拆分函数参数并将它们一个接一个地传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68454719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com