切换枚举时在 switch 语句中使用默认值

2022-01-19 00:00:00 enums switch-statement c++

在切换每个枚举都被一个案例覆盖的枚举时,您的程序是什么?理想情况下,您希望代码能够面向未来,您如何做到这一点?

What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you'd like the code to be future proof, how do you do that?

另外,如果某些白痴将任意 int 强制转换为枚举类型怎么办?是否应该考虑这种可能性?或者我们应该假设这样一个严重的错误会在代码审查中被发现?

Also, what if some idiot casts an arbitrary int to the enum type? Should this possibility even be considered? Or should we assume that such an egregious error would be caught in code review?

enum Enum
{
    Enum_One,
    Enum_Two
};

Special make_special( Enum e )
{
    switch( e )
    {
        case Enum_One:
            return Special( /*stuff one*/ );

        case Enum_Two:
            return Special( /*stuff two*/ );
    }
}

void do_enum( Enum e )
{
    switch( e )
    {
        case Enum_One:
            do_one();
            break;

        case Enum_Two:
            do_two();
            break;
    }
}

  • 不要使用默认情况,gcc 会警告你(Visual Studio 会吗?)
  • 使用 assert(false) 添加默认情况;
  • 添加引发可捕获异常的默认情况
  • 添加一个引发不可捕获异常的默认情况(它可能只是从不捕获它或总是重新抛出的策略).
  • 我没有考虑过的更好的东西
  • 我对你为什么选择以他们的方式做这件事特别感兴趣.

    I'm especially interested in why you choose to do it they way you do.

    推荐答案

    我抛出了一个异常.确实鸡蛋就是鸡蛋,有人会将一个具有错误值而不是枚举值的整数传递给您的开关,最好是大声失败,但让程序有可能处理错误,而 assert() 不会.

    I throw an exception. As sure as eggs are eggs, someone will pass an integer with a bad value rather than an enum value into your switch, and it's best to fail noisily but give the program the possibility of fielding the error, which assert() does not.

相关文章