根据C++标准,当枚举类型的值超出其范围时,会发生未定义行为。因此,比较枚举类型的值与其区间的边界值,即“first”和“last”,来确定其是否在范围内是安全的。以下是一个示例代码:
enum class Color { RED, GREEN, BLUE };
constexpr Color first = Color::RED;
constexpr Color last = Color::BLUE;
Color c = Color::GREEN;
if (c >= first && c <= last) {
// 在范围内
} else {
// 超出范围
}
上一篇:比较枚举类型的if语句
下一篇:比较枚举值会导致编译器错误