Lambda expressions—lambdas—are a game changer in C++ programming. That’s somewhat surprising, because they bring no new expressive power to the language. Everything a lambda can do is something you can do by hand with a bit more typing. But lambdas are such a convenient way to create function objects, the impact on day-to-day C++ software development is enormous. Without lambdas, the STL “
_if” algorithms (e.g.,
std::count_if, etc.) tend to be employed with only the most trivial predicates, but when lambdas are available, use of these algorithms with nontrivial conditions blossoms. The same is true of algorithms that can be customized with comparison functions (e.g.,
std::lower_bound, etc.). Outside the STL, lambdas make it possible to quickly create custom deleters for
std::shared_ptr (see Items 18 and 19), and they make the specification of predicates for condition variables in the threading API equally straightforward (see Item 39). Beyond the Standard Library, lambdas facilitate the on-the-fly specification of callback functions, interface adaption functions, and context-specific functions for one-off calls. Lambdas really make C++ a more pleasant programming language.
The vocabulary associated with lambdas can be confusing. Here’s a brief refresher:
A lambda expression is just that: an expression. It’s part of the source code. In