Endsieg77's Studio.

lambda expr

2020/12/31 Share

Basic Grammar

In C++, a lambda expression(Also a closure) is in a form as below:

1
[capture] [(parameters)] [mutable] [->return-type]{statement}

  1. [capture] Capture List. ‘[]’ functions as an introduction to a lambda expression;
    Essentially, lambda expression in C++ is functor, but it’s simpler and can be defined anywhere;
    The compiler judges if the following code is lambda function accoarding to the ‘[]’ introducer;
    The Capture List can capture the varibles in the context for lambda function to use;

  2. (parameters)Parameter List. Shares the similar rule with the ordinary function. Can be omitted if no parameter
    pass is required;

  3. mutablemutable identifier. Lambda functions will not change its parameters’ value, mutable can remove its constness;
    With the identifier, lambda functions parameter list cannot be omitted;

  4. ->return-typeReturn Type. Declare the return type of function using trailing-return-type;
    Can be omitted if no return value is required. We can also omit it when the return type can be easily deduced by compiler;

  5. {statement}Function Body;

More About Capture List

  1. [var]Capture var passed-by-value;
  2. [=]Capture all variables in the father block;
  3. [&var] Capture var passed-by-reference;
  4. [&]Capture all variables in the father block;
  5. [this]Explicitly capture “this” pointer;
  6. [x, y, , ..., &]Capture all variables before ‘&’ by value, and all others by reference;
  7. [&x, &y, ..., =]Similar to 6.;

Call at once

1
[capture](formal_params){statement}(real_params);

Currying(Nesting of Lambda Expressions)

1
[capture](params)->return-type{return [capture](params)->return-type{};}
CATALOG
  1. 1. Basic Grammar
  2. 2. More About Capture List
  3. 3. Call at once
  4. 4. Currying(Nesting of Lambda Expressions)