我有以下代码片段,虽然完全微不足道,但却说明了我试图在更通用的代码中使用的模式。
template<typename InT, typename ResT>
ResT unary_apply( InT val, std::function<ResT(InT)> fn )
{
return fn(val);
}
我希望能够使用函数指针、仿函数、lambda 等调用 unary_apply:因此使用 std::function
将其抽象化。
当我尝试按以下方式使用上述内容时,C++ (g++ 4.7) 无法执行相关类型推断:
double blah = unary_apply( 2, []( int v ) { return 3.0 * v; } );
失败
src/fun.cpp:147:75: error: no matching function for call to ‘unary_apply(int, test()::<lambda(int)>)’
src/fun.cpp:147:75: note: candidate is:
src/fun.cpp:137:6: note: template<class InT, class ResT> ResT unary_apply(InT, std::function<ResT(InT)>)
src/fun.cpp:137:6: note: template argument deduction/substitution failed:
src/fun.cpp:147:75: note: ‘test()::<lambda(int)>’ is not derived from ‘std::function<ResT(double)>’
而且我发现我必须显式指定模板参数(实际上我认为这只是不可推断的返回类型):
double blah = unary_apply<int, double>( 2, []( int v ) { return 3.0 * v; } );
我不太熟悉 C++11 中的类型推断规则,但上面的行为看起来确实合理(我可以看到通过 std::function
的内部机制进行推断可能是而是一个很大的问题)。我的问题是:是否有可能重写上面的 unary_apply
函数以保持相同的灵 active (就可以作为第二个参数传递的函数/仿函数等类型而言)同时还给出更多类型推断的线索,因此我不必在调用时显式提供模板参数?
最佳答案
多一点鸭子式应该可行:
template <typename T, typename F>
auto unary_apply(T&& val, F&& func) -> decltype(func(val)) {
return func(std::forward<T>(val));
}
关于使用 lambda 和 std::function 的 C++11 类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344063/