C++ 14 – lambda features
There are different lambda expression-related features introduced in C++ 14. The features include the usage of a lambda with auto, lambda capture expression with initializer, and generic lambda in STL algorithms.
Let us see this using an example C++ program. We ran this program on Ubuntu 22.04 machine. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/cpp14-lambda.cpp.
These are the header files required in the program.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
Here, we are using auto in arguments of lambda. It makes it generic or polymorphic. We can see that the same lambda expression is now used for both int and double sum calculations.
// lambda with auto
auto generic_sum = [](const auto& a, const auto& b) { return a + b; };
int int_sum = generic_sum(3, 4);
double double_sum = generic_sum(3.5, 4.5);
std::cout << "lambda - int sum: " << int_sum << ", double sum: " << double_sum << std::endl;
From C++ 14 onwards, we can use lambda capture (the [ ] box that we give to capture surrounding variables) for an initializer. Here, “y = x * 2” is an expression, not just a variable.
// Lambda capture expression with initializer
int x = 5;
auto capture_lambda = [y = x * 2] { return y; };
std::cout << "Lambda capture expression with initializer: " << capture_lambda() << std::endl;
We can use generic lambda as a function object in STL algorithms, as shown.
// Use lambda with STL algorithms
std::vector<double> numbers = {5.5, 1.1, 4.4, 2.2, 3.3};
std::sort(numbers.begin(), numbers.end(), [](const auto& a, const auto& b) { return a < b; });
std::cout << std::endl;
return 0;
}
The compilation and output of the program are as shown.
$ g++ -std=c++14 -o cpp14-lambda cpp14-lambda.cpp
$ ./cpp14-lambda
lambda - int sum: 7, double sum: 8
Lambda capture expression with initializer: 10