简体   繁体   English

使用lambda和std :: function的C ++ 11类型推断

[英]C++11 type inference with lambda and std::function

I have the following snippet of code, that although entirely trivial, illustrates a pattern I am trying to use in more general code. 我有以下代码片段,虽然完全无关紧要,但它说明了我试图在更通用的代码中使用的模式。

template<typename InT, typename ResT>
ResT unary_apply( InT val, std::function<ResT(InT)> fn )
{
    return fn(val);
}

I would like to be able to call unary_apply with function pointers, functors, lambdas etc: hence the use of std::function to abstract that all away. 我希望能够使用函数指针,函子,lambdas等调用unary_apply:因此使用std::function来抽象出所有这些。

When I try to use the above in the following way, C++ (g++ 4.7) is unable to perform the relevant type inference: 当我尝试以下列方式使用上述内容时,C ++(g ++ 4.7)无法执行相关的类型推断:

double blah = unary_apply( 2, []( int v ) { return 3.0 * v; } );

Failing with 失败了

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)>’

And I find that I have to explicitly specify the template parameters (in practice I believe it is just the return type that is not inferable): 而且我发现我必须明确指定模板参数(实际上我认为它只是不可推断的返回类型):

double blah = unary_apply<int, double>( 2, []( int v ) { return 3.0 * v; } );

I am not that familiar with the type inference rules in C++11, but the above behaviour does seem reasonable (I can see that inferring via the internal mechanics of std::function is probably rather a big ask). 我对C ++ 11中的类型推理规则并不熟悉,但上面的行为看起来确实合理(我可以看到通过std::function的内部机制推断可能是一个很大的问题)。 My question is: is it possible to re-write the unary_apply function above to keep the same flexibility (in terms of the types of functions/functors etc that can be passed as a second parameter) whilst also giving more of a clue to type inference so I do not have to explicitly supply the template parameters at the point of call? 我的问题是:是否有可能重新编写上面的unary_apply函数以保持相同的灵活性(就可以作为第二个参数传递的函数/函子类型而言),同时还提供了更多的类型推理线索所以我不必在通话点明确提供模板参数?

Going bit more duck-typey should work: 更多鸭子应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM