切换枚举类时删除重复

时间:2016-03-31 19:52:05

标签: c++11 enums

当我打开enum class时,我必须在每种情况下重申enum class。这是因为constexpr以外的问题 - 构造很难想象我还有什么意思。是否有通知编译器,如果匹配,块内的所有内容都应解析为我选择的enum class

考虑以下包含编译片段的示例,并考虑我想写的非编译片段(注释掉)。

#include <iostream>

enum class State : std::uint8_t;
void writeline(const char * msg);
void Compiles(State some);

enum class State : std::uint8_t
{
    zero = 0,
    one = 1
};

int main()
{
    Compiles(State::zero);
    return 0;
}

void Compiles(State some)
{
    switch (some)
    {
    case State::zero: //State::
        writeline("0");
        break;
    case State::one: //State::
        writeline("1");
        break;
    default:
        writeline("d");
        break;
    }
}


//void WhatIWant(State some)
//{
//  using State{ //this makes no sense to the compiler but it expresses what I want to write
//      switch (some)
//      {
//      case zero: //I want the compiler to figure out State::zero
//          writeline("0");
//          break;
//      case one: //I want the compiler to figure out State::one
//          writeline("1");
//          break;
//      default:
//          writeline("d");
//          break;
//      }
//  }
//}

void writeline(const char * msg)
{
    std::cout << msg << std::endl;
}

有没有办法使用switch语句并让编译器找出enum class,也许在给出一次提示之后?

1 个答案:

答案 0 :(得分:1)

enum class以某种方式进行设计,以便每次

}。

如果您不想在每个语句中使用State::前缀,只需使用c ++ 98中的旧式枚举。

注意:使用C ++ 11,您仍然可以使用类似于State:: enum MyEnym : std::uint8_t的常规枚举。