[英]Pass a function pointer with variable parameters as an argument in C++
我正在嘗試傳遞帶有可變參數的 function 作為我的 function baz()
的參數。 我不太確定如何 go 執行此操作,但希望我在下面提供的示例顯示了我當前的思考過程。
#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;
}
任何幫助是極大的贊賞。
您可以傳遞一個 function 類型
#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
Godbolt: https://godbolt.org/z/beMv6a9a4
或者您可以稍微改變您的方法,而不是自己傳遞參數,您可以讓 lambda 捕獲它們。
#include <iostream>
#include <type_traits>
// you can call foo with any invocable
// and even let it return the return value of that invocable.
template<typename fn_t>
auto foo(fn_t&& fn ) -> std::enable_if_t<std::is_invocable_v<fn_t>, decltype(fn())>
{
std::cout << "foo begin\n";
// slightly different handling for functions returning a void
if constexpr (std::is_same_v<decltype(fn()), void>)
{
fn();
std::cout << "foo end\n";
}
else
{
auto retval = fn();
std::cout << "foo end\n";
return retval;
}
}
void bar(int a, int b, std::string c)
{
std::cout << "Test a: " << a << " Test b: " << b << " Test c: " << c << "\n";
}
int baz(int x, int y)
{
std::cout << x + y << "\n";
return x + y;
}
int main()
{
int x{ 2 };
int y{ 3 };
foo([&] { bar(x, y, "Hello!"); } );
int sum = foo([&] { return baz(x,y); });
return sum;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.