標籤:

怎麼理解 `auto var = [&]() { /* things to do */ }`?


struct Fuck
{
int shit;
int bitch;

Fuck(int _shit, int _bitch)
:shit(_shit), bitch(_bitch)
{
}

void operator()()
{
cin &>&> shit &>&> bitch;
}
};

int main()
{
int shit, bitch;
Fuck var;
var(shit, bitch);
cout &<&< shit &<&< bitch; } ////////////////////////////////////////////// int main() { int shit, bitch; auto var = [](){ cin &>&> shit &>&> bitch;};
var();
cout &<&< shit &<&< bitch; }


看過一篇不錯的講解C++11 lambda的博客:

C++11 - Lambda Closures, the Definitive Guide

C++11/14 Rocks(http://cpprocks.com/books/)這本小書(clang版只有180頁)比較系統地介紹了C++11中的新特性,在講lambda時,有這麼一句話:

In fact, internally lambdas are implemented as classes with operator().

...

The compiler will generate the appropriate function object and pass an instance of it in place of the lambda expression.

至於這裡的auto,也是C++11中新增的type inference特性(auto、decltype、declval、……)。因為完整地寫出一個函數的原型是一件讓人不爽的事情,所以這裡就用auto,讓編譯器從初始化表達式自動推導出var的靜態類型了(如果不嫌麻煩,可以自己std::function&<...&>)。

其實,lambda、closure(閉包)這些概念我是在Python中接觸到的。哈哈。

-----


Lambda functions (since C++11)

a comma-separated list of zero or more captures, see below.

A list of symbols can be passed as follows:

  • [a,b] where a is captured by value and b is captured by reference.
  • [this] captures the this pointer by value
  • [] captures all automatic variables mentioned in the body of the lambda by reference
  • [=] captures all automatic variables mentioned in the body of the lambda by value
  • [] captures nothing


lambda么么噠~ 類似C#中() =&> { … }


A lambda expression is essentially a class, a constructor, and a function call operator.


lambda是一個比匿名函數強大得多的匿名函數類型。


lambda,拿到當前scope中的所有變數。



C++ Primer中文版第五版 P506

說的比較詳細吧~


推薦閱讀:

為什麼 C++ 列表初始化時會執行兩次拷貝構造函數?
寫循環語句,循環體部分理論上是不是可以都寫在for(;;)第二個分號後?
map key是一個複雜結構,為什麼無法插入?
C++構造函數參數列表初始化與直接在函數內部初始化有何區別?
C++ 的 string 為什麼不提供 split 函數?

TAG:C | C11 |