In C++, how does a generic lambda with auto parameters differ from a C++20 template lambda, and when do you need the template form?
answer
- call operator becomes a template
- each auto is its own parameter
- name T to tie parameters together
- requires-clauses and forwarding by T
basics
~20 sA generic lambda's auto parameters make its call operator a template with one independent type per auto. A C++20 template lambda, []<typename T>(...), names the type, so you can require two parameters to share it, use T in the body, or constrain it.
solid answer
~40 sBoth forms make the closure's `operator()` a **member function template**; one closure type serves every call. In a **generic lambda** (C++14), each `auto` parameter invents its own template parameter, so `[](const auto& a, const auto& b)` accepts unrelated types and the body can name those types only through `decltype`. A **template lambda** (C++20) writes `[]<typename T>(...)` and names the type. You need it when two parameters must share a type, as in `(const std::vector<T>& v, const T& fallback)`, which rejects a `std::vector<int>` with a `double`; when the body needs `T` itself; when you want a `requires`-clause; or to forward with `std::forward<T>` rather than `std::forward<decltype(x)>`. C++23 adds an explicit object parameter, `this auto self`, letting a lambda call itself.
code
cpp · 20 lines#include <cstdio>
#include <string>
#include <vector>
int main() {
// C++14 generic lambda: the call operator is a template, one parameter type each
auto greater = [](const auto& a, const auto& b) { return a > b; };
std::printf("%d %d\n", greater(3, 2.5), greater(std::string("b"), "a"));
// C++20 template lambda: name the type and tie parameters together
auto first_or = []<typename T>(const std::vector<T>& v, const T& fallback) {
return v.empty() ? fallback : v.front();
};
std::vector<int> clicks{4, 7};
std::printf("%d %d\n", first_or(clicks, -1), first_or(std::vector<int>{}, -1));
// C++23 explicit object parameter: a lambda that calls itself
auto depth = [](this auto self, int n) -> int { return n == 0 ? 0 : 1 + self(n - 1); };
std::printf("%d\n", depth(3));
}go deeper
Know that auto parameters let one lambda accept different argument types, much like a function template.
Explain that the call operator becomes a template, that each auto is independent, and when C++20's named template parameters are needed.
Use template lambdas with requires-clauses to fail bad calls at the call site, and know the C++23 explicit object parameter for recursion.
Set the team's readability bar: plain auto for short helpers, named templates and constraints only when parameters must agree or the type is needed.
## One closure, a templated call operator For an ordinary lambda the closure type has a plain function call operator. For a **generic lambda** the standard gives the closure type a **function call operator template** instead. There is still exactly one closure type per lambda expression; what multiplies is the set of `operator()` specializations, one per combination of argument types the program calls it with. The two spellings differ in how that template's parameters are declared. | Form | Since | How template parameters arise | What the body can name | |---|---|---|---| | `[](auto a, auto b)` | C++14 | each `auto` invents its own parameter | only `decltype(a)`, `decltype(b)` | | `[]<typename T>(T a, T b)` | C++20 | written explicitly, like a function template | `T` itself | | `[]<typename T>(T a) requires std::integral<T>` | C++20 | explicit, with constraints | `T`, checked by the concept | | `[](this auto self, int n)` | C++23 | explicit object parameter | `self`, the closure itself | ## Generic lambdas: independent auto parameters Each `auto` is a separate invented template parameter. In the code example, `greater` compares an `int` with a `double`, then a `std::string` with a string literal: four different argument types, two specializations, one closure. This is usually what you want for short helpers such as comparators and visitors. The limits show up when the body needs the type: - it cannot say "both arguments have the same type"; - it must write `std::decay_t<decltype(x)>` to get a plain type; - perfect forwarding needs `auto&& x` with `std::forward<decltype(x)>(x)`. ## Template lambdas: naming the type C++20 lets a lambda introducer carry an explicit template parameter list. That is the tool when: 1. **Parameters must agree.** `first_or` takes `const std::vector<T>&` and `const T&`. Calling it with a `std::vector<int>` and `2.5` fails deduction; Clang says `deduced conflicting types for parameter 'T' ('int' vs. 'double')`. The `auto` version would accept the call and convert silently. 2. **The body needs `T`.** Constructing `T{}`, declaring a `std::vector<T>`, or calling `sizeof(T)` is direct. 3. **You want constraints.** A `requires`-clause after the template parameter list, or a constrained parameter such as `<std::integral T>`, rejects bad calls at the call site with a readable diagnostic. 4. **You forward.** `[]<typename T>(T&& x) { use(std::forward<T>(x)); }` reads like any forwarding function template. A constrained form puts the rule in the signature: ```cpp auto scale = []<std::integral T>(T value, T factor) { return value * factor; }; scale(6, 7); // OK: T is int, returns 42 scale(6, 7L); // rejected: deduced conflicting types for parameter 'T' ('int' vs. 'long') scale(1.5, 2.0); // rejected: 'double' does not satisfy 'integral' ``` The quoted reasons are the notes Clang 21 printed for each rejected call under `-std=c++20`. Compiled as C++17, Clang 21 accepted the earlier template lambda only with `explicit template parameter list for lambdas is a C++20 extension`. ## Recursion through an explicit object parameter A lambda cannot name its own variable inside its initializer: `auto fact = [&fact](int n) { ... }` is rejected because a variable declared with `auto` cannot appear in its own initializer. **C++23** solves it with an **explicit object parameter**: `[](this auto self, int n) -> int { ... self(n - 1) ... }`. Here `self` is the closure object, and the call operator is a template deduced from how the lambda is called. Apple clang 21 compiles it under `-std=c++23`; under `-std=c++17` it reports `explicit object parameters are incompatible with C++ standards before C++2b`. ## Function pointer conversion A generic lambda with no captures still converts to a function pointer, through a conversion function **template**: `int (*fp)(int) = [](auto a) { return a; };` instantiates the call operator for `int`. ## Mistakes interviewers listen for - Believing a generic lambda creates a new closure type per call; it creates new `operator()` specializations. - Believing two `auto` parameters must have the same type. - Reaching for `std::function` to make a lambda recursive, when C++23's `this auto self` needs no wrapper. - Using a template lambda where plain `auto` was enough, and making a short helper harder to read.
- How do you perfectly forward an argument in a generic lambda without a template parameter list?Declare the parameter as `auto&& x` and forward with `std::forward<decltype(x)>(x)`. For an lvalue argument `decltype(x)` is an lvalue reference and the forward yields an lvalue; for an rvalue argument it is an rvalue reference and the forward yields an rvalue. The C++20 form `[]<typename T>(T&& x)` with `std::forward<T>(x)` does the same and reads like an ordinary forwarding function template.
- Does a generic lambda's body compile once or once per argument type?Once per distinct set of argument types it is called with, because each call instantiates a specialization of the call operator template. Errors in the body that depend on the parameter types therefore appear only for the argument types that trigger them, and every specialization adds code, just as an ordinary function template does.
- A generic lambda produces a new closure type for every call.
- Two auto parameters of a lambda must be called with the same type.
- A lambda must be wrapped in std::function before it can call itself.
- Template lambdas need C++23; C++20 offers only auto parameters.
- A generic lambda's auto parameters resolve their types at run time.
Assumes C++23: generic lambdas date from C++14, explicit template parameter lists from C++20, and explicit object parameters (this auto self) from C++23.