use*_*918 5 c++ lambda parentheses c++11
我对C++ 11 lambdas遇到的一些例子感到困惑.例如:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚最后的括号是做什么的.他们作为构造函数实例化lambda吗?鉴于lambda的模板是:
[capture_block](parameters) mutable exception_specification -> return_type {body}
Run Code Online (Sandbox Code Playgroud)
令我感到困惑的是,那些实例需要这些括号才能工作.有人可以解释他们为什么需要他们吗?
好吧,鉴于lambda表达式基本上是一个匿名函数,最后的括号只是调用这个函数.所以
result = [](const string& str){return "Hello World " + str;}("3!");
Run Code Online (Sandbox Code Playgroud)
等于
auto lambda = [](const string& str){return "Hello World " + str;};
string result = lambda("3!");
Run Code Online (Sandbox Code Playgroud)
这对于没有参数的lambda也是一样的,比如in
cout << []()->string{return "Hello World 1!";}() << endl;
Run Code Online (Sandbox Code Playgroud)
否则(如果没有调用)尝试输出lambda表达式,这本身不起作用.通过调用它只是输出结果std::string.
他们正在调用函数对象!
分两个阶段:
auto l = []()->string{return "Hello World 1!";}; // make a named object
l(); // call it
Run Code Online (Sandbox Code Playgroud)
lambda表达式求值为函数对象.由于没有operator<<带有这样一个函数对象的重载,如果你没有调用它来生成一个,你会收到一个错误std::string.
| 归档时间: |
|
| 查看次数: |
1302 次 |
| 最近记录: |