具有可变数量和类型的参数作为另一个函数的参数的 C++ 函数

pkt*_*iuk 3 c++ bind function

我想创建调用另一个函数并打印其参数的函数。
它应该与具有许多参数变量组合的许多函数(返回相同的结果)兼容。

我想要这样的东西:

int fun1(){}
int fun2(int i){}
int fun3(std::string s, int i){}

void execute_and_print(std::function f, ...)
{
///code
}

int main()
{
execute_and_print(&fun1);
execute_and_print(&fun2, 3);
execute_and_print(&fun3,"ff",4);
}
Run Code Online (Sandbox Code Playgroud)

它可以打印:

executed function with arguments:
executed function with arguments: 3
executed function with arguments: ff, 4
Run Code Online (Sandbox Code Playgroud)

在 C++ 中也可能吗?

Cal*_*eth 5

在C++17中非常简单

template <typename F, typename... Args>
void execute_and_print(F f, Args... args)
{
    (std::cout << ... << args);
    f(args...);
}
Run Code Online (Sandbox Code Playgroud)

在此之前还有额外的仪式

template <typename F, typename... Args>
void execute_and_print(F f, Args... args)
{
    int dummy[] = { (static_cast<void>(std::cout << args), 0)... };
    f(args...);
}
Run Code Online (Sandbox Code Playgroud)