在 lambda 函数中使用 auto [英] Using auto in a lambda function
本文介绍了在 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 关键字在 C++11 中不能用作函数参数的类型.如果你不想在 lambda 函数中使用实际类型,那么你可以使用下面的代码.
auto keyword does not work as a type for function arguments, in C++11. 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);
});
问题中的代码在 C++ 14 中运行良好.
The code in the question works just fine in C++ 14.
这篇关于在 lambda 函数中使用 auto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文