Use Lambdas for Scoped Reusable Code
Learn to use lambdas for scoped reusable code.
Lambda expressions can be defined and stored for later use. They can be passed as parameters, stored in data structures, and called in different contexts with different parameters. They are as flexible as functions, but with the mobility of data.
How to do it
Let’s start with a simple program that we’ll use to test various configurations of lambda expressions:
We’ll first define a
main()
function and use it to experiment with lambdas:
int main() {... // code goes here}
Inside the
main()
function, we’ll declare a couple of lambdas. The basic definition of a lambda requires a pair of square brackets and a block of code in curly brackets:
auto one = [](){ return "one"; };auto two = []{ return "two"; };
Notice that the first example one
includes parentheses after the square brackets, and the second example two
does not. The empty parameter parentheses are commonly included, but are not always required. The return type is inferred by the compiler.
We can call these functions with
cout
, or withformat
, or in any context that will take a C-string:
cout << one() << '\n';cout << format("{}\n", two());
In many cases, the compiler can determine the return type from automatic type deduction. Otherwise, we can specify the return type with the
->
operator:
auto one = []() -> const char * { return "one"; };auto two = []() -> auto { return "two"; };
Lambdas use the trailing return type syntax. This consists of the ->
operator followed by the type specification. If the return type is not specified, it is considered auto
. If we use a trailing return type, the parameter parentheses are required. ...