Jun 272012
 

In my opinion, the single biggest addition to C++11 is the Lambda function and expressions (for more features in C++ click here…).

Look at the case when you are calling std::sort function, you have to specify the comparator function and then pass that function as an argument to std::sort. In such situations, you may want to specify the function at the point of calling std::sort inline. Because that function (Comparator Function) has not other use but to be called to this API. This function may not even have a name , we don’t really care.. 

In C++11, you can specify anonymous functions, called lambda function (or expression).  It is of the form:

    [capture_list] (parameter_list)->return_type { function_body }

For Example:

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

capture_list : This list specify the variables of enclosing function which are passed either by-reference or by-value. In the above example the list is empty. But it can have values to be passed to the function.

  • [ ]        list is empty than no object of enclosing function can be used in lambda function.
  • [=]      All the variables of enclosing function will be used by-value in the lambda function.
  • [&]      All the variables of enclosing function will be used by-reference in the lambda function.
  • [x , &y]   x is passed by value and y by reference.
  • [& , x]     x is passed by value and all other by reference.
  • [= , &x]  x is passed by reference and all other by value.

parameter_list : parameter list of lambda function (Similar to the parameter list of a normal function).

return_type : You can ignore this if it can be derived by the decltype of return expression.

function_body : Body of the function.

Usage Example:

If we want to compute the sum of squares of all the elements in a vector, then one way to do it using lambda function is as below

    std::vector<int> v;
    int squareSum = 0;
    std::for_each(v.begin(), v.end(), [&](int x) { squareSum += x * x; } );

 

Previous: Separate Null Pointer in C++11

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)