在lambda函数中使用auto [英] Using auto in a lambda function

查看:414
本文介绍了在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆