我正在尝试将一个具有可变数量参数的函数作为参数传递给我的函数 baz()
。我不太确定如何去做这件事,但希望下面提供的示例能够展示我当前的思考过程。
#include <iostream>
template<typename... Ts>
void foo(void (*func)(Ts...)){
func(Ts...);
}
void bar(int a, int b, std::string c){
std::cout << "Test a: " << a << " Test b: " << b << " Test c: " << c << "\n";
}
void baz(int x, int y){
std::cout << x+y << "\n";
}
int main()
{
foo(&bar, 10, 20, "Hello!"); // Expected: "Test a: 10 Test b: 20 Test c: Hello!"
foo(&baz, 2, 2); // Expected: "4"
// main.cpp:13:12: error: expected primary-expression before ‘...’ token
return 0;
}
非常感谢任何帮助。
最佳答案
您可以传递函数类型
#include <iostream>
template<typename Fn, typename ... Ts>
void foo( Fn&& func, Ts...ts ){
func(ts...);
}
void bar(int a, int b, std::string c){
std::cout << "Test a: " << a << " Test b: " << b << " Test c: " << c << "\n";
}
void baz(int x, int y){
std::cout << x+y << "\n";
}
int main()
{
foo(&bar, 10, 20, "Hello!"); // Expected: "Test a: 10 Test b: 20 Test c: Hello!"
foo(&baz, 2, 2); // Expected: "4"
return 0;
}
产品
Program stdout
Test a: 10 Test b: 20 Test c: Hello!
4
关于c++ - 在 C++ 中传递带有可变参数的函数指针作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75155223/