Skip to main content
A C++ template lambda is a lambda expression that explicitly declares a template parameter list, introduced in C++20. It extends the C++14 generic lambda (which relies on auto parameters) by allowing developers to name the template parameters directly. This enables precise type constraints, exact type extraction, and simplified perfect forwarding without requiring decltype or std::decay_t boilerplate.

Syntax Anatomy

The template parameter list is enclosed in angle brackets < > and is positioned immediately after the capture clause [ ] and before the function parameter list ( ).
Basic Example:

Compiler Translation (The Closure Class)

Under the hood, the compiler translates a template lambda into an unnamed closure class containing a templated operator(). The lambda expression above is functionally equivalent to the following compiler-generated structure:

Technical Mechanics vs. C++14 Generic Lambdas

In C++14, generic lambdas use auto to deduce types, which implicitly creates a template parameter for each auto argument. C++20 template lambdas solve specific mechanical limitations of the auto approach.

1. Enforcing Identical Types

With C++14 generic lambdas, enforcing that two parameters share the exact same type requires static_assert and type traits. Template lambdas enforce this at the signature level.

2. Perfect Forwarding

Forwarding an auto parameter in C++14 requires decltype to deduce the value category. Template lambdas allow direct use of the named template parameter T.

3. Extracting Inner Types

When passing a templated container (like std::vector) to a lambda, C++14 requires typename decltype(container)::value_type to access the underlying element type. Template lambdas allow pattern matching on the parameter type directly.

Integration with C++20 Concepts

Template lambdas natively support C++20 Concepts for constrained template parameters. The constraints can be applied directly in the template parameter list or via a requires clause.

Parameter Pack Support

Template lambdas fully support variadic template parameter packs, allowing the lambda to accept an arbitrary number of arguments of varying types while retaining the ability to expand the pack explicitly.
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More