问题描述
我有以下模板.
当我在代码中使用它时,我指定了模板参数.为什么编译器无法为我推断出这一点?我必须如何更改我的模板定义才能使其正常工作?
When I use it in my code I have the specify the template parameters. Why is the compiler not able to deduce this for me? How do I have to change my template definition to make this work?
可运行代码:http://ideone.com/FjGnxd
这个问题的原始代码来自这里:标准::transform-like 函数,返回转换后的容器
The original code in this question comes from here: The std::transform-like function that returns transformed container
推荐答案
您的函数需要一个 std::function
参数,但您正在使用 lambda 表达式调用它.两者不是同一类型.lambda 可以转换到std::function
,但模板参数推导需要完全匹配,并且不考虑用户定义的转换.因此推演失败.
Your function expects an std::function
argument, but you're calling it with a lambda expression instead. The two are not the same type. A lambda is convertible to std::function
, but template argument deduction requires exact matches and user defined conversions are not considered. Hence the deduction failure.
如果您实际上将 std::function
传递给 map()
,则推导确实有效.
Deduction does work if you actually pass an std::function
to map()
.
现场演示
避免必须指定模板参数的一种可能解决方法是修改函数以接受任何类型的可调用对象,而不是 std::function
对象.
One possible workaround to avoid having to specify the template arguments is to modify the function to accept any kind of callable, rather than an std::function
object.
相同想法的另一个版本,使用 decltype
和 declval
而不是 result_of
Another version of the same idea, using decltype
and declval
instead of result_of
最后,使用尾随返回类型
Finally, using a trailing return type
现场演示
这篇关于编译器不推导出模板参数(映射 std::vector -> std::vector)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!