【问题标题】:Access enum entries from anonymous struct从匿名结构访问枚举条目
【发布时间】:2017-05-15 22:01:00
【问题描述】:

我有这样的代码:

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: 而不将我的结构命名为一个(这显然有效)。

这个:

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)

           ^

【问题讨论】:

  • 里面有问题吗?我没看到。
  • @EOF - 我很好奇是否可以添加案例条目:无需将我的结构命名为 one
  • case entry: 代码适用于我当编译为 C 而不是 C++ 时
  • @MichałWalenciak 你指的是main.cpp,但标签是C。

标签: c++ gcc struct enums enumeration


【解决方案1】:

可以写:

case decltype(data.en)::entry:

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

【讨论】:

  • 这看起来很糟糕 :) 还有一点好笑
  • 有趣的解决方案 :) 谢谢
【解决方案2】:

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

【讨论】:

  • 很好。乍一看有点奇怪,但还是蛮有道理的。
猜你喜欢
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多