C++ Stateless Lambda Expressions

ht‮spt‬://www.theitroad.com

In C++, a lambda expression is an anonymous function object, which can be used as an argument to a function call, stored as a variable or member, or used to define a local function. It is a convenient way to write concise and readable code that can be used in various contexts.

A stateless lambda expression is a lambda that does not capture any variables from its surrounding scope. The syntax for a stateless lambda expression is as follows:

[] (parameters) -> return_type {
    // lambda body
}
  • The square brackets [] indicate that the lambda is stateless and does not capture any variables.
  • The parameters specify the input arguments to the lambda, similar to a regular function declaration.
  • The return_type is the data type returned by the lambda, which can be omitted if the lambda returns void.
  • The lambda body contains the statements that make up the function logic.

Here is an example of a stateless lambda expression that takes two integer arguments and returns their sum:

auto sum = [] (int a, int b) -> int {
    return a + b;
};

int result = sum(3, 4); // result = 7

Note that the keyword auto is used to automatically infer the type of the lambda expression, which is a function object that takes two int arguments and returns an int.