【发布时间】:2012-07-05 12:10:55
【问题描述】:
我有以下 sn-p 的代码,虽然完全微不足道,但说明了我试图在更通用的代码中使用的模式。
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_applyfunction 以保持相同的灵活性(就可以作为第二个参数传递的函数/函子等类型而言)同时也提供更多线索类型推断,所以我不必在调用点显式提供模板参数?
【问题讨论】:
标签: c++ lambda c++11 type-inference