括号在C ++ 11 lambda表达式的结尾 [英] Parentheses at the end of a C++11 lambda expression
问题描述
我困惑了一些例子,我遇到了与C ++ 11 lambdas。
例如:
I am confused with some of the examples that I have come across with C++11 lambdas. For eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << []()->string{return "Hello World 1!";}() << endl;
[]{cout << "Hello World 2!" << endl;}();
string result = [](const string& str)->string {return "Hello World " + str;}("2!");
cout << "Result: " << result << endl;
result = [](const string& str){return "Hello World " + str;}("3!");
cout << "Result: " << result << endl;
string s;
[&s](){s = "Hello World 4!";}; // does not work
cout << s << endl;
[&s](){s = "Hello World 4!";}(); // works!
cout << s << endl;
return 0;
}
我无法弄清楚最后的括号是什么。他们实例化,作为一个构造函数,lambda?假定lambda的模板是:
I am unable to figure out what the parentheses at the end are doing. Are they instantiating, as a constructor, a lambda? Given that the template for a lambda is:
[capture_block](parameters) mutable exception_specification -> return_type {body}
这让我很担心,那些实例需要那些括号。
it baffles me that those parentheses are required for those instances to work. Can someone explain what they are why they are required?
推荐答案
很好,由于lambda表达式基本上是一个匿名函数,圆括号在结尾只做调用此函数。
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!");
等效于
auto lambda = [](const string& str){return "Hello World " + str;};
string result = lambda("3!");
对于没有参数的lambda,同样的方式也是如此,例如
This holds in the same way for a lambda with no arguments, like in
cout << []()->string{return "Hello World 1!";}() << endl;
否则(如果未调用)尝试输出一个lambda表达式,工作。通过调用它只是输出结果 std :: string
。
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
.
这篇关于括号在C ++ 11 lambda表达式的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!