Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using auto in a lambda function

#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?

like image 550
BЈовић Avatar asked Oct 10 '11 07:10

BЈовић


People also ask

What is auto lambda expression?

Immediately invoked lambda expression is a lambda expression which is immediately invoked as soon as it is defined. For example, #include<iostream> using namespace std; int main(){ int num1 = 1; int num2 = 2; // invoked as soon as it is defined auto sum = [] (int a, int b) { return a + b; } (num1, num2);

What is the correct way to use a lambda function?

Syntax. Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

Can you call a function in a lambda?

The whole lambda function lambda x : x * x is assigned to a variable square in order to call it like a named function. The variable name becomes the function name so that We can call it as a regular function, as shown below. The expression does not need to always return a value.

How do you pass a lambda function in C++?

Permalink. All the alternatives to passing a lambda by value actually capture a lambda's address, be it by const l-value reference, by non-const l-value reference, by universal reference, or by pointer.


1 Answers

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.

like image 123
Jagannath Avatar answered Oct 02 '22 16:10

Jagannath