Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++20 not allow to call a generic lambda with an explicit type? [duplicate]

Tags:

c++

lambda

c++20

auto f1 = []<typename T>(T) { return T{}; };
auto f2 = []<typename T>()  { return T{}; };

int main()
{
    f1(1);     // ok
    f2<int>(); // err: expected primary-expression before 'int'
}

Why does C++20 not allow to call a generic lambda with an explicit type?

like image 382
xmllmx Avatar asked Apr 24 '21 07:04

xmllmx


People also ask

How do you call a lambda in C++?

A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke ). If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.

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

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. Additionally, they detect when you implicitly copy the this pointer. This means a significant cause of undefined behavior with lambdas is gone.

Does C have lambda function?

Significance of Lambda Function in C/C++ Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store.


Video Answer


1 Answers

The correct syntax to invoke overloaded template operator () function supplying template parameters is

auto f1 = []<typename T>(T) { return T{}; };
auto f2 = []<typename T>()  { return T{}; };

int main()
{
    f1(1);     // ok
    f2.operator ()<int>(); // Ok
}

https://godbolt.org/z/YzY7njPGh

like image 111
user7860670 Avatar answered Oct 24 '22 16:10

user7860670