Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is lambda functions type? C++ [duplicate]

See my code:

#include <iostream>
#include <typeinfo>

int main() {
    auto x = [](int a, int b) -> bool{return a<b;};
    std::cout<<typeid(decltype(x)).name()<<std::endl;
}

And this is printing Z4mainEUliiE_. Can anyone explain whay? And what is the actual type of x??

like image 403
Eduard Rostomyan Avatar asked Jan 02 '23 18:01

Eduard Rostomyan


1 Answers

The actual type of a lambda is specified as a "unique closure type" that corresponds to the lambda expression.

Its name isn't specified. Its layout even isn't fully specified. It's almost entirely an implementation defined type, of a name one usually doesn't know nor care about.

And when you think about it, you (the developer) don't really need to know what its "actual name" is. You can refer to it just fine:

using my_lambda_type = decltype(x);

There's another aspect to your question, that beyond the closure type being implementation defined, the behavior of std::type_info::name is itself implementation defined. You are printing an implementation defined name for an implementation defined type via an entirely implementation defined mechanism.

There's very little you can glean (C++-wise) from it other than details about your current compiler implementation.

like image 139
StoryTeller - Unslander Monica Avatar answered Jan 12 '23 17:01

StoryTeller - Unslander Monica