簡體   English   中英

C ++ 11 lambda表達式末尾的括號

[英]Parentheses at the end of a C++11 lambda expression

我對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;
}

我無法弄清楚最后的括號是做什么的。 他們作為構造函數實例化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也是一樣的,比如in

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

否則(如果沒有調用)嘗試輸出lambda表達式,這本身不起作用。 通過調用它,它只是輸出生成的std::string

他們正在調用函數對象!

分兩個階段:

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

lambda表達式求值為函數對象。 由於沒有operator<< overload需要這樣的函數對象,如果你沒有調用它來產生std::string ,你會收到錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM