A Bite of Lambda in C++11
12 Mar 2019 Languages C/C++ Lambda closureUpon the strong suggestion from a senior student, I recently studied and practiced a very advanced syntax sugar, Lambda expressions, introduced in C++11. This post talks about the basic of lambda expressions.
Syntax Example
Unlike Python, there is no keyword in C++ for lambda expressions,
but a special sequence of braces []
, parentheses ()
, and brackets {}
.
The full declaration in C++11 is [capture](params) -> ret {body}
,
as shown in the following example:
The lambda expression is like a function pointer that can be passed as a parameter when invoking a routine. Here comes an example using the lambda expression defined above:
In the C++ Primer Plus book,
lambda expression is compared with function pointer,
and functor (a struct
or class
having operator()
defined as a member method,
so that can be used as a function, PresumGen
in above exmaple).
Lambda expression has four advantages over the other two,
as summaried by the author:
- proximity
programmers can find the defination nearby where it is used (even inside a function call), while you cannot nest the definitions of functions. - brevity
it takes less coding to define and use a lambda expression than function pointer (no need to find a good name for the function, being anonymous) and functor (nostruct
orclass
header). - efficiency
it is more likely for compiler to choose inline a lambda expression (or functor), but function pointer is an address implies non-inline function. - capability
withcapture
, lambda expression can have the same scope as where it is defined. For example,[&]
provides access to all variables by references,[x]
means capturing variablex
by copy it value.eq
andIterFill
in the above example code illustrate the usage ofcapture
. This is very difficult for function pointer or functor to achieve the same effect.
Credits
- Thanks to the senior student who pushed me out of comfort zone to learn such an interesting syntax sugar.
- Stephen Prata - Thanks to your book “C++ Primer Plus”, where I learnt C++.
- cppreference.com - A great website for reference of C++.
- What is a lambda expression in C++11? - Thanks Flexo♦ and AAEM pmr for their answers.
- C++ priority_queue with lambda comparator error - Thanks the examples in this thread.