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?
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.
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With