Why “auto” is not acceptable as lambda parameter

穿精又带淫゛_ 提交于 2019-12-23 19:14:31

问题


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


回答1:


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;


来源:https://stackoverflow.com/questions/32646362/why-auto-is-not-acceptable-as-lambda-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!