"C++11" new feature--lambda function

Source: Internet
Author: User

This post consists of: http://www.sollyu.com/c11-new-lambda-function/

Article List

This article is a series of articles

The use of the "c++11" new feature--auto http://www.sollyu.com/c11-new-features-auto/

"C++11" new feature--lambda function http://www.sollyu.com/c11-new-lambda-function/

Description

in standard C + +, especially when using C + + standard library algorithm functions such as sort and find , users often want to be able to define a temporary statement function (predicate function) near the algorithm function call.

Because the language itself allows you to define types within a function, you can consider using function objects, but this is often cumbersome and redundant, and it hinders the flow of code. In addition, standard C + + does not allow a type defined inside a function to be used in a template, so the foregoing approach is not feasible.

C++11 support for Lambda solves the above problem.

A lambda function can be defined in the following way:

[](int x, int y) {return x + y;}
Specifying the return type

The return type of this unnamed function is decltype(x+y) . The return type can be ignored only if the lambda function conforms to the " return expression " form. In the foregoing case, the lambda function can only be a statement.

In a more complex case, the type of return can be explicitly specified as follows:

[](int x, int y), int {int z = x + y; return z + x;}

In this example, a temporary parameter z is created to store the intermediate result. As with the general function, the z value of the 不会保留到 next time the anonymous function is called again.

If a lambda function returns 没有 a value (for example, void), its return type can be completely ignored.

Parameter references that are defined in the same scope as the lambda function can also be used. This set of parameters is generally referred to as a closure (closure).

Style description
 []   [ x   &  Span class= "Nx-member" >y  ]  //x is transferred by value (preset) and y is transferred by reference.  [ &  ]  // Any external variables that are used are implicitly referenced by reference.  [ =  ]  //any external variables used Implicitly referenced by a value.  [ &,   x  The span class= "CP" >   [ =   &  The span class= "NB" >z  ]  

Closure is defined and used as follows:

std::Vector<int> somelist;int  Total = 0;std::For_each(somelist.begin(), somelist.End(), [& Total](int x) {   Total += x;});std::cout <<  Total;

The above example calculates the sum of the somelist elements and prints them out.

The parameter total is part of the lambda function closure and is passed into the predicate function as a reference, so its value can be changed by the lambda function.

If you do not use a referenced symbol & , the 参数以传值的方式传入 lambda function is represented.

This notation allows the user to clearly distinguish the method of parameter passing: 传值,或是传参考 .

Because the lambda function can not be used in place where it is declared (such as placing std::function objects);

In this case, if the parameter is linked to the closure in a reference way, it is meaningless or even dangerous behavior.

If the lambda function is used only at defined scopes, you can [&] declare the lambda function, representing all parameters referenced in the stack, in a reference way, without having to explicitly specify one by one:

std::Vector<int> somelist;int  Total = 0;std::For_each(somelist.begin(), somelist.End(), [&](int x) {   Total += x;});

The way a parameter passes in to a lambda function may vary with the real thing, and the general expectation is that the lambda function retains its scope function's stack pointer to access the zone parameter.

If not [=] , the [&] representation is used for the value of the 所有的参考的参数 pass.

For different parameters, the transfer value or the reference can be mixed and used. For example, the user can have all the parameters used in a reference way, but with a parameter used for the value of the pass:

int  Total = 0;int value = 5;[&, value](int x) {  Total += (x * value); };

Total is passed in as a reference to the lambda function, while value is the value of the pass.

If a lambda function is defined in a member function of a type, it is treated as a friend of that type. A lambda function like this can use a reference to an object of that type and be able to access members within it.

[](SomeType *typeptr) {typeptr->someprivatememberfunction ();};

This only works if the scope created by the lambda function is inside the member function of SomeType.

In the member function, the object's this pointer must be explicitly passed in to the lambda function, otherwise the lambda function in the member function cannot use any of the object's arguments or functions.

[this] () {this->someprivatememberfunction ();};

In the case of a lambda function, it is [&] [=] this visible in the lambda function.

A lambda function is a function object of the compiler's subordinate type, and this type name is available only to the compiler itself. If the user wants to pass in a lambda function as a parameter, the type must be a template type, or a std::function must be created to get the value of the lambda. Using the Auto keyword allows us to store lambda functions:

 auto    mylambdafunc    =    [ this  Span class= "P" > "()    {   this  ->  someprivatememberfunction   ();    };  auto    myonheaplambdafunc    =    new    auto   ([ =  ]     {   /*...*/   });  

However, if a lambda function obtains all of its closure parameters in a reference, or if there are no closure parameters, the resulting function object is given a special type: the std::reference_closure<R(P)> R(P) function signature that contains the return type.

std::functionThis will be the more efficient representation of the lambda function:

std: : reference_closure < void ()>mylambdafunc= [  this] (){ this-  Someprivatememberfunction(); }; Mylambdafunc ();

C++11 new attribute--lambda function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.