从匿名结构访问枚举条目

Access enum entries from anonymous struct

本文关键字:枚举 访问 结构      更新时间:2023-10-16

我有这样的代码:

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)

这是意料之中的。我很好奇我是否可以在不将我的结构命名为 one 的情况下添加case entry:(这显然有效(。

这:

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();
}