What is a generic (template) lambda?
Short answer
A generic lambda (C++14) uses auto for one or more parameters, making operator() a template so the lambda works with any argument types. C++20 adds explicit template parameter syntax.
Advertisement
AModel answer
A generic lambda (C++14) uses auto for one or more parameters, making operator() a template so the lambda works with any argument types. C++20 adds explicit template parameter syntax. Generic lambdas enable writing reusable, type-agnostic inline functions, often used with algorithms over varied types.
auto print = [](const auto& x) { std::cout << x; };
print(42); print("hi"); // works for both
// C++20 explicit form
auto f = []<typename T>(T x) { return x + x; };Real-world example
A single generic lambda logs elements of containers holding different value types.
Likely follow-ups
- What does auto in a parameter create? | What did C++20 add?
Related topics