c++ - C++11 lambda 表达式末尾的括号

标签 c++ lambda c++11 parentheses

我对使用 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/

相关文章:

java - 迭代 HashMap 时引用局部变量 -> 从 lambda 表达式引用的局部变量必须是最终的或有效的最终错误

c++ - nullptr 的运算符 <<(流输出)

c++ - 对 Makefile.win 中函数的 undefined reference

c# - 匿名类型的属性列表

c++ - MSVC10/11 中缺少统一初始值设定项的宏/内联函数解决方法

c++ - 如何映射 Linux 系统线程 id 和 std::thread::id?

通用模板 ostream << 运算符的 C++ 不明确重载

c++ - 确保模板参数类型与其可变构造函数的类型匹配

c++ - CCEventListener.cpp - 尝试实现触摸功能时断言失败

java - java8中,如何在lambdas foreach block 中设置全局值?