What is a lambda expression in C++11? When would I use one? What class of problem do they solve that wasn't possible prior to their introduction?
A few examples, and use cases would be useful.
c++c++-faqc++11lambda
What is a lambda expression in C++11? When would I use one? What class of problem do they solve that wasn't possible prior to their introduction?
A few examples, and use cases would be useful.
Best Answer
The problem
C++ includes useful generic functions like
std::for_each
andstd::transform
, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function.If you only use
f
once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off.In C++03 you might be tempted to write something like the following, to keep the functor local:
however this is not allowed,
f
cannot be passed to a template function in C++03.The new solution
C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the
struct f
. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form:Lambda functions are just syntactic sugar for anonymous functors.
Return types
In simple cases the return type of the lambda is deduced for you, e.g.:
however when you start to write more complex lambdas you will quickly encounter cases where the return type cannot be deduced by the compiler, e.g.:
To resolve this you are allowed to explicitly specify a return type for a lambda function, using
-> T
:"Capturing" variables
So far we've not used anything other than what was passed to the lambda within it, but we can also use other variables, within the lambda. If you want to access other variables you can use the capture clause (the
[]
of the expression), which has so far been unused in these examples, e.g.:You can capture by both reference and value, which you can specify using
&
and=
respectively:[&epsilon, zeta]
captures epsilon by reference and zeta by value[&]
captures all variables used in the lambda by reference[=]
captures all variables used in the lambda by value[&, epsilon]
captures all variables used in the lambda by reference but captures epsilon by value[=, &epsilon]
captures all variables used in the lambda by value but captures epsilon by referenceThe generated
operator()
isconst
by default, with the implication that captures will beconst
when you access them by default. This has the effect that each call with the same input would produce the same result, however you can mark the lambda asmutable
to request that theoperator()
that is produced is notconst
.