如何编写一个函数调用指定参数的任何指定函数(或函数对象)?
这是我尝试过的:
#include <iostream>
#include <functional>
using namespace std;
template <typename RetType, typename... ArgTypes>
RetType q(function<RetType(ArgTypes...)> f, ArgTypes... args)
{
return f(args...);
}
int h(int a, int b, int c) { return a + b + c; }
int main()
{
auto r = q(h, 1, 2, 3);
cout << "called, result = " << r;
return 0;
}
编译器说,由于类型“std::function<_Res(_ArgTypes ...)>”和“int (*)(int, int, int)”不匹配,模板参数推导/替换失败。
我不确定为什么不能在我的代码中推导出模板参数。
最佳答案
因为无论如何它都是一个模板,所以您根本不需要 std::function
。只需这样做:
template <class F, class... Arg>
auto q(F f, Arg... arg) -> decltype(f(arg...))
{
return f(arg...);
}
更好的是,使用完美转发:
template <class F, class... Arg>
auto q(F f, Arg&&... arg) -> decltype(f(std::forward<Arg>(arg)...))
{
return f(std::forward<Arg>(arg)...);
}
关于c++ - 调用任何指定函数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31439909/