Lambdas(C++11新增)

Lambdas 语法


  • no parameters: […] {…}

    [] {
         std::cout << "hello lambda" << std::endl;
       }
    

    You can call it directly:

     [] {
          std::cout << "hello lambda" << std::endl;
        } (); // prints ‘‘hello lambda’’
    

    or pass it to objects to get called:

    auto l = [] {
                  std::cout << "hello lambda" << std::endl;
                };
    ...
    l(); // prints ‘‘hello lambda’’
    
  • has parameters: […] (…) {…}

    A lambda can have parameters specified in parentheses, just like any other function:

    auto l = [] (const std::string& s) 
    {
        std::cout << s << std::endl;
    };
    l("hello lambda"); // prints ‘‘hello lambda’’
    
  • It cannot be templates.

  • return something. Without any specific definition of the return type, it is
    deduced from the return value. For example, the return type of the following lambda is int:

    [] {
        return 42;
       }
    

    Others, the following lambda returns 42.0:

    [] () -> double {
                     return 42;
                    }
    

Captures (Access to Outer Scope)


  • [=] means that the outer scope is passed to the lambda by value. Thus, you can read but not
    modify all data that was readable where the lambda was defined.

  • [&] means that the outer scope is passed to the lambda by reference. Thus, you have write access
    to all data that was valid when the lambda was defined, provided that you had write access there.For example:

    int x=0;
    int y=42;
    
    auto qqq = [x, &y] {
         std::cout << "x: " << x << std::endl;
         std::cout << "y: " << y << std::endl;
         ++y; // OK
         // ++i; // ERROR!!!!!
    };
    
    x = y = 77;
    qqq();
    qqq();
    std::cout << "finaly: " << y << std::endl;
    

    OUTPUT:

    x: 0
    y: 77
    x: 0
    y: 78
    finaly: 79
    

    Instead of [x, &y], you could also have specified [=, &y] to pass y by reference and all other
    objects by value.

  • multable

    To have a mixture of passing by value and passing by reference, you can declare the lambda as mutable. In that case, objects are passed by value, but inside the function object defined by the lambda, you have write access to the passed value. For example:

    int id = 0;
    auto f = [id] () mutable {
    std::cout << "id: " << id << std::endl;
    ++id; // OK
    };
    id = 42;
    f();
    f();
    f();
    std::cout << id << std::endl;
    

    has the following output:

    id: 0   
    id: 1
    id: 2
    42
    

Type of Lambdas


Using Lambdas


本文来源:《C++ Standard Library》(2nd Edition) Typed By:IFuMI

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值