在lambda函数中使用自动

问题描述 投票:39回答:4
#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 ); } );
}

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

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

这是否意味着在Lambda表达式中不应使用关键字auto

此作品:

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

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

c++ c++11 auto lambda
4个回答
67
投票
在C ++ 11中,

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


22
投票

C ++ 14允许自动声明lambda函数(通用lambda函数)参数。


20
投票

[Herb Sutter在采访中对此进行了简短的讨论。实际上,您对auto参数的要求与要求any


4
投票

lambda的类型需要在编译器甚至可以实例化std::for_each之前就知道。另一方面,即使理论上可行,也只能通过查看仿函数的调用方式来推导auto之后才能推导出for_each

如果有可能,请忽略for_each,并使用基于范围的循环更为简单:

© www.soinside.com 2019 - 2024. All rights reserved.