Search code examples
c++c++14c++20generic-lambda

What is the need of template lambda introduced in C++20 when C++14 already has generic lambda?


introduced generic lambdas that made it possible to write following:

auto func = [](auto a, auto b){
    return a + b;
};
auto Foo = func(2, 5);
auto Bar = func("hello", "world");

It is very clear that this generic lambda func works just like a templated function func would work.

Why did the C++ committee decide to add template syntax for generic lamda?


Solution

  • C++14 generic lambdas are a very cool way to generate a functor with an operator () that looks like this:

    template <class T, class U>
    auto operator()(T t, U u) const;
    

    But not like this:

    template <class T>
    auto operator()(T t1, T t2) const; // Same type please
    

    Nor like this:

    template <class T, std::size_t N>
    auto operator()(std::array<T, N> const &) const; // Only `std::array` please
    

    Nor like this (although this gets a bit tricky to actually use):

    template <class T>
    auto operator()() const; // No deduction
    

    C++14 lambdas are fine, but C++20 allows us to implement these cases without hassle.