Exploring Generic Lambdas and Lambda Templates
Build on the fundamentals of generic lambdas and lambda templates in this lesson.
We'll cover the following...
Lambdas, which are formally called lambda expressions, are a simplified way to define function objects in the place where they are needed. This typically includes predicates or comparison functions passed to algorithms. Although we won’t discuss lambda expressions in general, let’s take a look at the following examples:
int arr[] = { 1,6,3,8,4,2,9 };std::sort(std::begin(arr), std::end(arr),[](int const a, int const b) {return a > b; });int pivot = 5;auto count = std::count_if(std::begin(arr), std::end(arr),[pivot](int const a) {return a > pivot; });
Lambda expressions are syntactic sugar, a simplified way of defining anonymous function objects. When encountering a lambda expression, the compiler generates a class with a function-call operator. For the previous example, these could look as follows:
struct __lambda_1{inline bool operator()(const int a, const int b) const{return a > b;}};struct __lambda_2{__lambda_2(int & _pivot) : pivot{_pivot}{}inline bool operator()(const int a) const{return a > pivot;}private:int pivot;};
The names chosen here are arbitrary, and each compiler will generate different names. Also, the implementation details may differ, and the ones seen here are the bare minimum a compiler is supposed to generate. Notice that the difference between the first lambda and the second is that the latter contains state that it captures by value.
Type of lambdas
Lambda expressions, which were introduced in C++11, have received several updates in later versions of the standard. There are notably two, which will be discussed in this section:
Generic lambdas, introduced in C++14, allow us to use the
auto
specifier instead of explicitly specifying types. This transforms the generated function object into one with a template function-call operator.Template lambdas, introduced in C++20, allow us to use the template syntax to explicitly specify the shape of the templatized function-call operator.
To understand the difference between ...