3

We had the generic lambdas before C++20 and could write something like this.

   auto l = [](auto a, auto b)
   {
       return a+b;
   };

And then C++20 introduced template lambdas where we can write something like this

   auto l = []<typename T>(T a, T b)
   {
       return a+b;
   };

Or this

   auto l = []<typename T>(T a, auto b)
   {
       return a+b;
   };

Can someone explain what is the difference?
To be more specific, what template lambdas can achieve that was impossible with pre C++20 generic lambdas?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76

2 Answers2

4
auto l = [](auto a, auto b)

This lambda can be called with two completely different parameters. a can be an int, and b can be a std::string.

auto l = []<typename T>(T a, T b)

This lambda must be called with two parameters that have the same type. T, like in a regular template, can only be a single, specific, type.

This is the main difference. Pre-C++20 you can probably achieve mostly the same thing with a static_assert, but this simplifies it.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
4

One use case that I find useful is immediate call

[]<std::size_t... Is>(std::index_sequence<Is...>)
{
    // ...
}(std::make_index_sequence<N>());

pre-template lambda, you have to create helper function.

Jarod42
  • 203,559
  • 14
  • 181
  • 302