在切换枚举时在switch语句中使用默认值 [英] Using default in a switch statement when switching over an enum

查看:505
本文介绍了在切换枚举时在switch语句中使用默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

切换枚举时,您的过程是什么,其中每个枚举都由一个案例覆盖?



此外,如果一些idiot对enum类型转换一个任意的int呢?是否应该考虑这种可能性?

 枚举枚举
{
Enum_One,
Enum_Two
};

特殊make_special(枚举e)
{
开关(e)
{
case Enum_One:
return特殊* /);

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

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

case Enum_Two:
do_two();
break;
}
}





  • 使用 assert(false)添加默认大小写;
  • >
  • 添加一个引发可捕获异常的默认情况

  • 添加一个默认情况,引发一个不可捕获的异常



我特别感兴趣

解决方案

我抛出异常。如果鸡蛋是鸡蛋,有人会传递一个错误值的整数,而不是枚举值到你的交换机,最好是失败,但让程序有可能发生错误,而assert()没有。 / p>

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?

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

  • leave off the default case, gcc will warn you (will visual studio?)
  • add a default case with a assert(false);
  • add a default case that throws a catchable exception
  • add a default case that throws a non-catchable exception (it may just be policy to never catch it or always rethrow).
  • something better I haven't considered

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

解决方案

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.

这篇关于在切换枚举时在switch语句中使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆