This course has already ended.

Short Sidetrack: Lambdas in C++ [](){}

Lambdas are small anonymous functions you can write into code when you locally need a small code snippet as a function that will have no futher use. Lambdas are expecially useful with library algoritms, e.g. for_each. Qt’s connect also accepts a lambda as a slot.

../../_images/lambda_en.png

Lambdas can be compared to literals. A definition int const var = 0; is comparable to the function definition

void double (int param) {
    return 2*param;
}

Similarly the same functionality with a lambda [](int param){ return 2*param; } compares to the literal 0.

Examples of a lambda:

std::vector<int> v;
std::for_each(v.begin(), v.end(), [](int var){ ++var });
std::vector<int> values;
int input = 0;
std::cin >> input;
auto iter = std::find_if( values.begin(), values.end(),
                          [input](int curr){ return ( input < curr ); });

Let’s focus on the syntax of lambdas a little bit.

() parameter list. Contains the parameters of the lambda like in named functions.

-> return value. The return value can be ommitted if it is void or can be determined from the code (return statement).

{} lambda body. The body can be arbitrarily complex. HJowever, it is sensible to keep lambdas short and concise.

[] capture. The capture lets the lambda capture parts of its context, i.e. helps the lambda be aware of its surroundings. Lambda can also get information through its parameters, but as lambdas are often used with library functions, parameters are not enough to pass all the relevant information to the lambda. The capture can be

  • [&] captures all variables used in the lambda by reference
  • [& var] capture by reference
  • [=] captures all variables used in the lambda by value
  • [&, var] captures variables like with [&], but var by value
  • [=, &var] captures variables like with [=], but var by reference

Lambda can also be stored if needed.

auto lambda = [&](int var){env = var;};

The type must be auto as the lambda is compiler generated and thus only the compiler knows the type.

Qt’s connect can also use lambdas

connect( sender, &Sender::valueChanged,
         receiver, &Receiver::updateValue);

connect( sender, &Sender::valueChanged,
 [=]( const QString &newValue ) { receiver->updateValue( "senderValue", newValue ); } );
Posting submission...