Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "auto" is not acceptable as lambda parameter [duplicate]

Why does this code make a compile error?

std::find_if(std::begin(some_list), std::end(some_list), [](const auto& item){
//some code
});

The error of course at "auto"? why is not possible to know the type automatically ? thanks

like image 449
Humam Helfawi Avatar asked Jun 21 '26 01:06

Humam Helfawi


1 Answers

This is because as of C++11, lambda functions in C++ cannot be defined generically, therefore you cannot declare a parameter using auto. This has been added in the C++14 (and is already supported by some compilers).

However, you can achieve the same thing in C++11 using decltype(), in you case:

std::find_if(std::begin(some_list), std::end(some_list), [](decltype(*some_list.begin())& item){
        return item > 4;
like image 79
syntagma Avatar answered Jun 23 '26 14:06

syntagma