Search⌘ K
AI Features

Template Parameter for Lambdas

Explore the improvements in C++20 lambdas by learning how template parameters increase flexibility and safety. Understand the differences between typed, generic, and template lambdas, with examples showing type deductions and usage with containers. Gain practical knowledge on how these features improve lambda usability and correctness.

With C++20, lambda expressions support template parameters, and hence concepts can be default-constructed and support copy assignment when they have no state. Additionally, lambda expressions can be used in unevaluated contexts. With C++20, they detect when you implicitly copy the this pointer. This means a significant cause of undefined behaviorAll bets are open. Your program can produce the correct result, the wrong result, crashes during run-time, or may not even compile. That behavior might change when porting to a new platform, upgrading to a new compiler or as a result of an unrelated code change. with lambdas is gone.

Let’s start with template parameters for lambdas.

The subtle differences between different lambdas

Admittedly, the differences between typed lambdas (C++11), generic lambdas (C++14), and template lambdas (template parameter for lambdas) in C++20 are subtle.

C++
#include <iostream>
#include <string>
#include <vector>
auto sumInt = [](int fir, int sec) { return fir + sec; };
auto sumGen = [](auto fir, auto sec) { return fir + sec; };
auto sumDec = [](auto fir, decltype(fir) sec) { return fir + sec; };
auto sumTem = []<typename T>(T fir, T sec) { return fir + sec; };
int main() {
std::cout << '\n';
std::cout << "sumInt(2000, 11): " << sumInt(2000, 11) << '\n';
std::cout << "sumGen(2000, 11): " << sumGen(2000, 11) << '\n';
std::cout << "sumDec(2000, 11): " << sumDec(2000, 11) << '\n';
std::cout << "sumTem(2000, 11): " << sumTem(2000, 11) << '\n';
std::cout << '\n';
std::string hello = "Hello ";
std::string world = "world";
// std::cout << "sumInt(hello, world): " << sumInt(hello, world) << '\n';
std::cout << "sumGen(hello, world): " << sumGen(hello, world) << '\n';
std::cout << "sumDec(hello, world): " << sumDec(hello, world) << '\n';
std::cout << "sumTem(hello, world): " << sumTem(hello, world) << '\n';
std::cout << '\n';
std::cout << "sumInt(true, 2010): " << sumInt(true, 2010) << '\n';
std::cout << "sumGen(true, 2010): " << sumGen(true, 2010) << '\n';
std::cout << "sumDec(true, 2010): " << sumDec(true, 2010) << '\n';
// std::cout << "sumTem(true, 2010): " << sumTem(true, 2010) << '\n';
std::cout << '\n';
}

Before discussing the output, I want to compare the four lambdas:

  • sumInt

    C++ version Type of lambda Types of parameters
    C+11 Typed lambda Accepts only types
    convertible to int
...