C++ 具有强类型枚举的 Switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9062082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Switch Statements with strongly typed enumerations
提问by mark
When using strongly typed enums in a switch statement is there a way to avoid explicit casts to int
?
在 switch 语句中使用强类型枚举时,有没有办法避免显式转换为int
?
/// @desc an enumeration of the states that the session can be in.
enum class State
{
Created,
Connected,
Active,
Closed
};
State sesState = session->GetState();
switch (static_cast<int>(sesState))
{
case static_cast<int>(Session::State::Created):
// do stuff.
break;
case static_cast<int>(Session::State::Connected):
// do stuff.
break;
}
From the n3242 draft:
从 n3242 草案:
6.4.2 The switch statement [stmt.switch]
6.4.2 switch 语句[stmt.switch]
2 The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3).
2 条件应为整数类型、枚举类型或存在单个非显式转换函数到整数或枚举类型的类类型 (12.3)。
Does enumeration typeinclude strongly typed enums or are they incompatible with switch
statements because they require an explicit conversion to int
?
枚举类型是否包括强类型枚举,或者它们是否与switch
语句不兼容,因为它们需要显式转换为int
?
回答by Some programmer dude
An enumeration type is still an enumeration type even whether strongly typed or not, and have always worked fine in switch
statements.
枚举类型仍然是枚举类型,即使是强类型与否,并且在switch
语句中始终可以正常工作。
See this program for example:
例如,请参阅此程序:
#include <iostream>
enum class E
{
A,
B
};
int main()
{
E e = E::A;
switch (e)
{
case E::A:
std::cout << "A\n";
break;
case E::B:
std::cout << "B\n";
break;
}
}
The output of this is "A".
这个的输出是“A”。