Using auto in a lambda function

BЈовић picture BЈовић · Oct 10, 2011 · Viewed 28.2k times · Source
#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

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

This works :

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

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

Answer

Jagannath picture Jagannath · Oct 10, 2011

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);         
 });

The code in the question works just fine in C++ 14.