在lambda函数中使用auto

编程入门 行业动态 更新时间:2024-10-28 12:27:22
本文介绍了在lambda函数中使用auto的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <vector> #include <algorithm> void foo( int ) { } int main() { std::vector< int > v( { 1,2,3 } ); std::for_each( v.begin(), v.end(), []( auto it ) { foo( it+5 ); } ); }

编译时,上面的示例启动错误输出,如下所示:

When compiled, the example above starts the error output like this :

h4.cpp: In function 'int main()': h4.cpp:13:47: error: parameter declared 'auto' h4.cpp: In lambda function: h4.cpp:13:59: error: 'it' was not declared in this scope

这是不是意味着关键字 auto 不应该在lambda表达式中使用?

Does it mean that the keyword auto should not be used in lambda expressions?

这样工作:

std::for_each( v.begin(), v.end(), []( int it ) { foo( it+5 ); } );

为什么带auto关键字的版本不起作用?

Why the version with the auto keyword doesn't work?

推荐答案

auto关键字不能作为函数参数的类型。如果您不想在lambda函数中使用实际类型,则可以使用下面的代码。

auto keyword does not work as a type for function arguments. If you don't want to use the actual type in lambda functions, then you could use the code below.

for_each(begin(v), end(v), [](decltype(*begin(v)) it ){ foo( it + 5); });

更多推荐

在lambda函数中使用auto

本文发布于:2023-10-08 23:59:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474129.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   lambda   auto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!