gpt4 book ai didi

c++ - 将 vector 项传递给参数数量未知的函数对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:13 25 4
gpt4 key购买 nike

这是我想要实现的简化版本:

template <class Func, class Params>
void foo(Func f, Params p) {
f(p[0], p[1], ...) // <-- this is the problem. How to do this?
}
...
foo([](int a, int b){ cout<<(a+b); }, std::vector<int>{1,2});
foo([](char a){ cout<<a; }, std::vector<char>{'a'});

我希望问题很清楚。

编辑:

上面的例子没有很好的表达问题。我有一个 vector ,在较早的阶段填充了参数。我想要一个接受函数对象并使用 vector 中的参数调用它的函数。我可以假设 vector 大小等于参数的数量。

希望更好的例子:

class C {
std::vector<int> v;
public:
void add_param(int);
... // other functions that manipulate the vector in various ways

template<class Func>
void run(Func f) {
f(v[0], etc...); // <-- problem
}
};

最佳答案

您可以使用可变模板:

template <class Func, class... Params>
void foo(Func f, Params... p) {
f(p...);
}

foo([](int a, int b){ cout<<(a+b); }, 1, 2);
foo([](char a){ cout<<a; }, 'a');

关于c++ - 将 vector 项传递给参数数量未知的函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44518308/

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