Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

c++14 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?

like image 711
coder3101 Avatar asked Jan 10 '19 10:01

coder3101


People also ask

Why do we need lambda expressions in C++?

One of the new features introduced in Modern C++ starting from C++11 is Lambda Expression. It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument.

What is generic lambda in C++?

Generic lambdas were introduced in C++14 . Simply, the closure type defined by the lambda expression will have a templated call operator rather than the regular, non-template call operator of C++11 's lambdas (of course, when auto appears at least once in the parameter list).

Can you template lambda C++?

From the various lambda improvements, template parameters for lambdas are my favorite ones. Lambdas support with C++20 template parameters, can be default-constructed and support copy-assignment, when they have no state, and can be used in unevaluated contexts.

Can you template a lambda?

Lambda-expressions are not allowed in unevaluated expressions, template arguments, alias declarations, typedef declarations, and anywhere in a function (or function template) declaration except the function body and the function's default arguments.


2 Answers

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.

like image 157
Quentin Avatar answered Sep 20 '22 02:09

Quentin


Since you can use templated lambdas in C++20, you can restrict your types in an easier way than an SFINAE expression:

auto lambda = []<typename T>(std::vector<T> t){}; 

This lambda will work only with vector types.

like image 28
Antoine Morrier Avatar answered Sep 21 '22 02:09

Antoine Morrier