What is the use case for c++20 template lambdas?

Viewed 82

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?

2 Answers
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.

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.

Related