Why does a lambda expression return the type of a local enumeration class?

Why and how does it work? What type of auto is here?

auto lambda = [](){ enum class Local { X=0 }; return Local::X; }; auto x = lambda(); // No error! Why and what type is auto in this case? auto y = Local::X; // Error! Of course! 

enum class Local not known outside of the lambda type. This is a enum class and therefore cannot be of type int without an AFAIK throw. How can a local type be returned as auto and what type is it really outside of lambda?

+7
scope lambda type-safety c ++ 14 enum-class
source share
2 answers

Why and how does it work?

This works because:

  • the lambda expression causes the creation of a unique class and name at compile time.
    • The type of this class is called the internal compiler.
    • Therefore, the compiler may find something like <lambda_30560bd1c97ca682d011cd006c362574>::()::Local for x .

You can get the lambda type and then use it to declare objects of the enum class type contained in it:

 auto lambda = []() { enum class Local { X = 0, Z = 1 }; return Local::X; }; int main() { auto x = lambda(); // No error! Why and what type is auto in this case? //auto y = Local::X; // Error! Of course! using x_type = decltype(x); x_type y; y = x_type::Z; // can refer to enum members here y = x; } 

enum class Local not known outside of the lambda type a.

True, but an enum class is available if the corresponding namespace is allowed. Therefore, inside <lambda_30560bd1c97ca682d011cd006c362574>::()::Local you can enable Local inside lambda, but before compilation it is impossible to guess this name, but we can use decltype or auto to get the type.

This is a enum class and therefore cannot be of type int without cast

Correctly. But it still exists just as an enum class can exist inside a regular class or struct .

Without a known type, how can I continue to work with this value outside of lambda?

A utility of this type outside of lambda is limited. It is not int , but rather has its own unique type, so it does not really matter, even if it can be indirectly obtained.

+4
source share

This has nothing to do with lambdas or enum class es, it works for any local type in any function with an output type returned:

 auto f() { struct X {}; return X{}; } int main() { auto x = f(); } 

Type x cannot be directly referenced from the scope of an external function, but it is actually x defined in f .

+5
source share

All Articles