【发布时间】:2021-04-29 08:30:33
【问题描述】:
我想创建一个调用另一个函数并打印其参数的函数。
它应该与具有多种参数变量组合的许多函数(返回相同的结果)兼容。
我想要这样的东西:
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);
}
它可以打印:
executed function with arguments:
executed function with arguments: 3
executed function with arguments: ff, 4
在 C++ 中甚至可能吗?
【问题讨论】:
-
在 C++ 标签中查找“呼叫转移”,您会找到多种解决方案。关键是使
execute_and_print成为可变参数模板。这样它就可以调用你传递给它的任何函数。不过,它不会是std::function类型。 -
将其转换为 std::function 毫无意义,因为无论如何它都会被模板化。