Using default in a switch statement when switching over an enum(切换枚举时在 switch 语句中使用默认值)
问题描述
在切换每个枚举都被一个案例覆盖的枚举时,您的程序是什么?理想情况下,您希望代码能够面向未来,您如何做到这一点?
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.
这篇关于切换枚举时在 switch 语句中使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:切换枚举时在 switch 语句中使用默认值


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01