Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a lambda expression without both std::function and auto?

Tags:

c++

c++11

lambda

I have read the item31 of "Effective Modern C++" and web page of http://en.cppreference.com/w/cpp/language/lambda and wonder if I can define a lambda by its definite type instead of the wrapped type of std::function or keyword of auto and how can I accomplish that.

for instance, for the type int:

auto x_1 = 5; // type deduction
int x_2 = 5;  // defined by definite type
// both x_1, x_2 are int variables of value 5

now, when the problem comes to the lambda:

auto f_1_0 = []()->int{return 5;};
std::function<int(void)> f_1_1 = []()->int{return 5;};
SomeType f_2 = []()->int{return 5;}; // what's the SomeType here?
like image 430
Liu Weibo Avatar asked May 23 '26 21:05

Liu Weibo


1 Answers

Each lambda expression has its own unique type.

Here the expressions f_1 and f2 have different types.

auto f_1 = []()->int {return 5; }; 
auto f_2 = []()->int {return 5; }; 

Assigning f_2 = f_1 is illegal.

The standard says the types are "unnamed." In practice, the compiler probably makes up a new, hiiden typename for each lambda. Visual C++17 gave them the following names.

classmain::<lambda_7e9d7fb093569d78a8c871761cbb39d7>
classmain::<lambda_8f061a3967cd210147d6a4978ab6e125>

Not very useful information.

like image 143
Jive Dadson Avatar answered May 26 '26 10:05

Jive Dadson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!