Last updated:2026-10-12
C++20 Lambda Expressions (Part 1)¶
C++20: Lambda Templates¶
C++14 supports generic lambda expressions, which lets a lambda accept parameters of any type, for example:
which gets expanded into:
struct Func {
template <typename T1, typename T2>
auto operator()(T1 a, T2 b) const {
return a + b;
}
};
But it cannot produce the following kinds of expansions:
First: the same type
Second: only std::array
Third: no deduction
C++14 lambdas are nice, but C++20 lets us achieve these cases easily. C++20 allows lambda expressions to use template type parameters in their definition; here is the basic syntax:
The following examples show its benefits.
1. Type Constraints¶
In an example like the one below, C++14 lets us write this code, but what gets passed in at the call site is not necessarily a vector, so the behavior deviates from what was intended and errors follow.
With C++20 and later, we can constrain the type:
So here comes an interview question: in C++14, how would you constrain this to a vector safely?
2. Perfect Forwarding¶
In C++20 you can use perfect forwarding very easily, for example:
So, what is the advantage over C++14? Or put another way: what does it take to implement perfect forwarding in C++14?
That's all for this section.
Related Topics¶
- Getting Started with C++20 Coroutines | C++那些事
- C++20 channel in Practice | C++那些事
- C++20 Concepts | C++那些事
- C++20 constexpr and the Comma Expression | C++那些事
- C++20 Byte Order (endian) | C++那些事
- C++20 Modules | C++那些事
- C++20 Ranges Library | C++那些事
- C++20 std::span Design and Pitfalls | C++那些事
- A Guide to C++20 New Features | C++那些事
- C++20 [[likely]] and [[unlikely]] | C++那些事