C++11 Lambda運算式簡單解析

來源:互聯網
上載者:User

標籤:指定   ati   對象   attribute   實值型別   err   自己   調用   www   

C++11 新增了非常多特性,lambda 運算式是當中之中的一個。假設你想瞭解的 C++11 完整特性,

建議去http://www.open-std.org/看看新標準!


非常多語言都提供了 lambda 運算式,如 Python,Java 8

lambda 運算式能夠方便地構造匿名函數,假設你的代碼裡面存在大量的小函數,而這些函數一般僅僅被調用一次。那麼最好還是將他們重構成 lambda 運算式.

C++11 的 lambda 運算式規範例如以下:

[ capture ] ( params ) mutableexceptionattribute-> ret {body} (1)
[ capture ] ( params ) -> ret { body } (2)
[ capture ] ( params ) { body } (3)
[ capture ] { body } (4)

當中

  • (1) 是完整的 lambda 運算式形式。
  • (2) const 類型的 lambda 運算式,該類型的運算式不能改捕獲("capture")列表中的值。

  • (3)省略了傳回值類型的 lambda 運算式。可是該 lambda 運算式的傳回型別能夠依照下列規則推演出來:
    • 假設 lambda 代碼塊中包括了 return 語句,則該 lambda 運算式的傳回型別由 return 語句的傳回型別確定。
    • 假設沒有 return 語句。則類似 void f(...) 函數。
  • 省略了參數列表,類似於無參函數 f()。

mutable 修飾符說明 lambda 運算式體內的代碼能夠改動被捕獲的變數。而且能夠訪問被捕獲對象的 non-const 方法。

exception 說明 lambda 運算式是否拋出異常(noexcept)。以及拋出何種異常,類似於void f()throw(X, Y)。

attribute 用來聲明屬性。

另外,capture 指定了在可見域範圍內 lambda 運算式的代碼內可見得外部變數的列表。詳細解釋例如以下:

  • [a,&b] a變數以值的方式唄捕獲,b以引用的方式被捕獲。

  • [this] 以值的方式捕獲 this 指標。

  • [&] 以引用的方式捕獲全部的外部自己主動變數。
  • [=] 以值的方式捕獲全部的外部自己主動變數。
  • [] 不捕獲外部的不論什麼變數。

此外,params 指定 lambda 運算式的參數。

2個詳細的 C++11 lambda 運算式範例:

#include <vector>#include <iostream>#include <algorithm>#include <functional> int main(){    std::vector<int> c { 1,2,3,4,5,6,7 };    int x = 5;    c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } ), c.end());     std::cout << "c: ";    for (auto i: c) {        std::cout << i << ‘ ‘;    }    std::cout << ‘\n‘;     // the type of a closure cannot be named, but can be inferred with auto    auto func1 = [](int i) { return i+4; };    std::cout << "func1: " << func1(6) << ‘\n‘;      // like all callable objects, closures can be captured in std::function    // (this may incur unnecessary overhead)    std::function<int(int)> func2 = [](int i) { return i+4; };    std::cout << "func2: " << func2(6) << ‘\n‘; }//配合boost庫#include <boost/function.hpp>typedef boost::function<void(int)> fobject_t;// Now this function may accept functional objectsvoid process_integers(const fobject_t& f);#include <assert.h>#include <deque>int main() {    // lambda function with no parameters that does nothing    process_integers([](int /*i*/){});    // lambda function that stores a reference    std::deque<int> ints;    process_integers([&ints](int i){        ints.push_back(i);    });    // lambda function that modifies its content    std::size_t match_count = 0;    process_integers([ints, &match_count](int i) mutable {        if (ints.front() == i) {           ++ match_count;        }        ints.pop_front();    });    assert(match_count == 6);}void process_integers(const fobject_t& f) {    static const int data[] = {1, 2, 3, 4, 5, 200, 0};    std::for_each(data, data + 6, f);}


C++11 Lambda運算式簡單解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.