A Bite of Lambda in C++11

Upon 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 (no struct or class 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
    with capture, lambda expression can have the same scope as where it is defined. For example, [&] provides access to all variables by references, [x] means capturing variable x by copy it value. eq and IterFill in the above example code illustrate the usage of capture. This is very difficult for function pointer or functor to achieve the same effect.

Credits