一个名为test
的函数以std::function<>
作为其参数。
template<typename R, typename ...A>
void test(std::function<R(A...)> f)
{
// ...
}
但是,如果我执行以下操作:
void foo(int n) { /* ... */ }
// ...
test(foo);
编译器(gcc 4.6.1)提示:no matching function for call to test(void (&)(int))
。为了使最后一行 test(foo)
编译并正常工作,我该如何修改test()
函数?在 test()
函数中,我需要类型为std::function<>
的f
函数。我的意思是,有没有一些模板技巧能让编译器确定函数(例如
foo
)的签名,并自动将其转换为 std::function<void(int)>
?
test
定义为可接受任何东西(T
)的模板。因为std::function
也不会直接拒绝不兼容的函数对象,所以在此限制函数模板参数类型的目标似乎对我来说并不是太有用。 - Johannes Schaub - litb(T)
,但是如何将其转换为std::function<R(A...)>
?似乎可以使用std::result_of<>
获取R
,但是A...
呢? - Daniel K.