本文介绍了在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
发布评论