More about Lambda Expressions
Function objects are powerful, but every time we use a function object we need to define a class for it, which has a poor flexibility. In many cases we don't want to explicitly define a class, then we can use lambda expressions instead.
In previous chapters we have already used lambda expressions a lot. Lambda expression is also known as an anonymous function since it can serve as a function without being given a name. A lambda function has the following syntax:
The following example is a lambda expression which prints "Hello World" to the console. We use a function object to store it and call the function with operator =
.
With lambda expression, the compiler will automatically generate a function object class for as, something like this:
Another example use lambda expression to calculate the sum of two integers:
This expression is equivalent to using a function object looks like:
Inside the square brackets []
is the external variables we want to lambda expression to capture. Its usage is as follows:
[]
: No external variable is captured.[=]
: All external variables are captured and passed by value.[&]
: All external variables are captured and passed by reference.[this]
:*this
pointer of an object is captured.[=, &a]
: All external variables are captured and passed by value, but a is passed by reference.[a, b]
: a and b are captured and passed by value.
Now if we have lambda expression which takes two value and swap their values. Obviously, we should pass these two values by reference here:
It is equal to have a function object with two member variables which are initialized by reference, and operator ()
swap these two variables.
Since lambda expression is actually a function object, we can use std::function to store it as well. The following example is a map whose key is an integer and value is a std::function object with two int parameters and return type int. Then we can use this map to store lambda expressions of arithmetic operations.
Last updated