C++11 使用 lambda 和 std::function 进行类型推理

C++11 type inference with lambda and std::function

本文关键字:类型 推理 function C++11 lambda std 使用      更新时间:2023-10-16

我有以下代码片段,虽然完全是微不足道的,但说明了我试图在更通用的代码中使用的模式。

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 函数以保持相同的灵活性(就可以作为第二个参数传递的函数/函子等类型而言),同时还提供更多类型推断的线索,所以我不必在调用时显式提供模板参数?

多一点鸭子类型应该可以:

template <typename T, typename F>
auto unary_apply(T&& val, F&& func) -> decltype(func(val)) {
    return func(std::forward<T>(val));
}