Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument type auto deduction and anonymous lambda functions

Tags:

c++

c++11

lambda

Lets say I have these lines of code;

std::vector<int> ints; std::for_each(ints.begin(), ints.end(), [](int& val){ val = 7; }); 

However, I dont want to specify the argument type in my lambda functions, ie, I want to write something like this;

std::for_each(ints.begin(), ints.end(), [](auto& val){ val = 7; }); 

Is there anyway this can be achieved?

(boost::lambda doesn't need types to be specified...)


Update:

For now I use a macro: #define _A(container) decltype(*std::begin(container)) so I can do:

std::for_each(ints.begin(), ints.end(), [](_A(ints)& val){ val = 7; }); 
like image 384
Viktor Sehr Avatar asked Apr 19 '11 07:04

Viktor Sehr


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 use of lambda functions in C++?

Mutable specification Typically, a lambda's function call operator is const-by-value, but use of the mutable keyword cancels this out. It doesn't produce mutable data members. The mutable specification enables the body of a lambda expression to modify variables that are captured by value.

Are lambdas always Inlined?

All lambdas are inline. Not all calls to them are necessarily inlined.


1 Answers

No. "Polymorphic lambdas" is what this feature was referred to during the C++ committee discussions, and it was not standardized. The parameter types of a lambda must be specified.

You can use decltype though:

std::for_each(ints.begin(), ints.end(), [](decltype(*ints.begin())& val){ val = 7; }); 
like image 167
Anthony Williams Avatar answered Oct 16 '22 18:10

Anthony Williams