Alex Rivera | Logout

Argument type auto deduction and anonymous lambda functions

Asked 2011-04-19T07:10:41.333
34

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

1 Answer

30

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; });
answered 2011-04-19T07:32:21.927

Your Answer