C++ Lambda Expressions
Introduction
C++ lambda expression defines an anonymous function object (a closure) that could be passed as an argument to a function. Recently I just realized that my knowledge about the usages of lambda expression had been quite limited.
In this blog post, I would like to document the usages of lambda expression which I knew and did not know.
Examples
1 |
|
To compile the program, please run the following command in the terminal.
1 | $ g++ lambda_expression.cpp -o lambda_expression -std=c++14 |
Usages
Typical Usages
Typically, a lambda expression consists of three parts: a capture list []
, an optional parameter list ()
and a body {}
, all of which can be empty. One of the simplest lambda expressions is
1 | [](){} |
Since the parameter list ()
is optional, actually the simplest lambda expression is
1 | []{} |
Lambda expression could be passed to or assigned to function pointers and std::function
, or passed to function template.
Capture List
Capture list is used to make the variables outside the lambda expression accessible inside the lambda expression, via copy or reference. This is somewhat similar to C++ functor which could also change the inner state of the function object.
1 | // Capture by reference |
Parameter List
Parameter list is just like the parameter list for ordinary functions. To allow compile-time polymorphism, we could use template function or auto
as the type for arguments and let the compiler to deduct during compile time.
1 | auto f5 = [](auto x){return 2 * x;}; |
Function Body
Function body has nothing special.
Return Type
By default, the return type of the lambda expression could be deduced by the compiler at compile time. We could also optionally include the return type in the lambda expression to ask the compiler to double-check it and cast the type on it for us.
1 | auto f3 = [rate](double x)->double{return (1 + rate) * x;}; |
Conclusions
I actually did not know how to use the capture list previously. Making a good use of it would make life a lot easier in some scenarios.
C++ Lambda Expressions