Parentheses at the end of a C++11 lambda expression

烈酒焚心 提交于 2019-11-30 21:48:06

Well, given that a lambda expression is basically an anonymous function, the parentheses at the end do nothing more than just call this function. So

result = [](const string& str){return "Hello World " + str;}("3!");

is just equivalent to

auto lambda = [](const string& str){return "Hello World " + str;};
string result = lambda("3!");

This holds in the same way for a lambda with no arguments, like in

cout << []()->string{return "Hello World 1!";}() << endl;

which would otherwise (if not called) try to output a lambda expression, which in itself doesn't work. By calling it it just puts out the resulting std::string.

They're calling the function object!

In two phases:

auto l = []()->string{return "Hello World 1!";}; // make a named object
l(); // call it

A lambda expression evaluates to a function object. Since there's no operator<< overload that takes such a function object, you'd get an error if you didn't call it to produce a std::string.

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