我对使用 C++11 lambda 遇到的一些示例感到困惑。 例如:
#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 的模板是:
[capture_block](parameters) mutable exception_specification -> return_type {body}
让我感到困惑的是,那些实例需要那些括号才能工作。有人可以解释为什么需要它们吗?
最佳答案
好吧,鉴于 lambda 表达式基本上是一个匿名函数,最后的括号只是调用这个函数。所以
result = [](const string& str){return "Hello World " + str;}("3!");
就等同于
auto lambda = [](const string& str){return "Hello World " + str;};
string result = lambda("3!");
这对于没有参数的 lambda 也是一样的,比如
cout << []()->string{return "Hello World 1!";}() << endl;
否则(如果未调用)会尝试输出 lambda 表达式,这本身不起作用。通过调用它,它只会输出结果 std::string
。
关于c++ - C++11 lambda 表达式末尾的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662688/