All Recipes
Home/Other Features/Lambda Capture Improvements
intermediate

Lambda Capture Improvements

New lambda capture features in C++20

Example Code

cpp
#include <iostream>
#include <vector>
#include <algorithm>
struct Widget {
int id;
std::string name;
};
int main() {
// C++20: Capture structured bindings
std::pair<int, std::string> pair{42, "answer"};
auto [num, str] = pair;
auto lambda1 = [num, str]() {
std::cout << str << ": " << num << std::endl;
};
lambda1(); // answer: 42
// C++20: Template lambdas
auto print_all = []<typename T>(const std::vector<T>& vec) {
for (const auto& item : vec) {
std::cout << item << " ";
}
std::cout << std::endl;
};
std::vector<int> nums = {1, 2, 3};
std::vector<std::string> words = {"hello", "world"};
print_all(nums); // 1 2 3
print_all(words); // hello world
// C++20: Lambdas in unevaluated contexts
using Comparator = decltype([](int a, int b) { return a < b; });
// C++20: Default-constructible stateless lambdas
auto cmp = []<typename T>(const T& a, const T& b) { return a < b; };
decltype(cmp) another_cmp; // Default construct!
std::cout << another_cmp(1, 2) << std::endl; // 1 (true)
return 0;
}

Explanation

C++20 enhances lambdas with structured binding capture, template syntax for explicit type parameters, use in unevaluated contexts, and default construction of stateless lambdas.

Key Points

  • 1Capture structured bindings directly
  • 2Template lambdas with <typename T>
  • 3Use in decltype and sizeof
  • 4Stateless lambdas are default-constructible