从匿名结构访问枚举条目

Access enum entries from anonymous struct

我有这样的代码:

struct
{
    enum
    {
        entry,
    } en;

} data;

void foo()
{
    switch(data.en)
    {
    }
}

这给了我一个警告:

main.cpp:13:11: warning: enumeration value 'entry' not handled in switch [-Wswitch]

     switch(data.en)

这是预期的。我很好奇我是否可以添加 case entry: 而无需将我的结构命名为 one(这显然有效)。

这个:

struct
{
    enum
    {
        entry,
    } en;

} data;

void foo()
{
    switch(data.en)
    {
        case entry:
        break;
    }
}

给出错误+警告:

main.cpp: In function 'void foo()':

main.cpp:15:14: error: 'entry' was not declared in this scope

         case entry:

              ^~~~~

main.cpp:13:11: warning: enumeration value 'entry' not handled in switch [-Wswitch]

     switch(data.en)

           ^

可以写:

case decltype(data.en)::entry:

但是我认为它不会被认为是好的代码。

在 C 中,您可以按以下方式进行

#include <stdio.h>

struct
{
    enum
    {
        entry,
    } en;

} data = { entry };

void foo()
{
    switch ( data.en )
    {
        case entry:
            puts( "Hello, World!" );
            break;
    }
}

int main( void )
{
    foo();
}

在 C++ 中,您可以按以下方式进行

#include <iostream>

struct
{
    enum
    {
        entry,
    } en;

} data = { decltype( data.en )::entry };

void foo()
{
    switch ( data.en )
    {
        case data.entry:
            std::cout <<  "Hello, World!" << std::endl;
            break;
    }
}

int main()
{
    foo();
}