Function Objects and Lambda Expressions

Lambda expressions: versatility and functionality

Lambda expressions, introduced in C++11, and further enhanced with every C++ version since, are one of the most useful features in modern C++. Their versatility comes not only from easily passing functions to algorithms but also their use in a lot of circumstances where we need to pass the code around, especially as we can store a lambda in a std::function.

Although lambdas made these programming techniques vastly simpler to work with, everything mentioned in this section is possible to perform without them.

A lambda—or, more formally, a lambda expression—is a convenient way of constructing a function object. But instead of using lambda expressions, we could instead implement classes with operator() overloaded, and then instantiate these to create function objects.

The basic syntax of a C++ lambda

In a nutshell, lambdas enable programmers to pass functions to other functions just as easily as a variable is passed.

Let's compare passing a lambda to an algorithm with passing a variable:

Get hands-on with 1400+ tech skills courses.