简体   繁体   中英

Why can't I define an unnamed enum in the return type of a lambda function?

This code:

void f() {
    auto determineType = []() -> enum {Type_ONE, Type_TWO} {
            return Type_ONE;
    };
}

fails to compile:

testcase-enum-in-lambda.cpp:3:36: error: unnamed enumeration must be a definition

Why isn't this allowed in C++? It is very clear what this does. The unnamed enum can be associated with the definition of the lambda and could have the same scope. I don't see any problems related to such a construct, except that it probably isn't specified in the C++ standard.

Why isn't this allowed in C++?

Explicit return type in lambda expresses the type you are returning, it does not define a new type.

[]() -> Type { }

As far as I know, allowing a type definition here is a novel idea that isn't yet expressed in C++.

C++ supports type deduction (via decltype prior to c++14, automatically after). Type deduction can appear to be defining a new type as in this example from cppreference.com

template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) // return type depends on template parameters
                                      // return type can be deduced since C++14
{
    return t + u;
}

but despite decltype(t + u) appearing to identify a previously undeclared type, even in this case the type is either T, U, or some other pre-defined type V operator+(T, U)

What's wrong with doing something like this? It's no good declaring a return type that's only known by the lambda...


typedef enum 
{ 
    Type_ONE, 
    Type_TWO 
}
teTypes;


void f() 
{
    auto determineType = []() -> teTypes 
    {
        return teTypes::Type_ONE;
    };
}

FYI I recommend Ivan Cukic's book: https://www.amazon.co.uk/Functional-Programming-C-Ivan-Cukic/dp/1617293814

It contains a good description about what the C++ compiler does for you in the background to make lambdas work (generating a class in the background etc).

Also see https://blog.feabhas.com/2014/03/demystifying-c-lambdas/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM