在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;
}
从n3242草案中:
6.4.2切换语句stmt.switch
2条件应为整型、枚举型或存在单个非显式转换函数到整型或枚举型的类类型(12.3)。
枚举类型是否包括强类型枚举,或者它们与switch
语句不兼容,因为它们需要显式转换为int
发布于 2012-01-30 18:18:30
枚举类型仍然是枚举类型,即使是强类型还是非强类型,并且在switch
语句中总是工作得很好。
例如,请参阅此程序:
#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;
}
}
它的输出是"A“。
https://stackoverflow.com/questions/9062082
复制相似问题