如何将 C++11 枚举类用于标志
假设我有这样一个类:
enum class Flags : char
{
FLAG_1 = 1;
FLAG_2 = 2;
FLAG_3 = 4;
FLAG_4 = 8;
};
现在我可以有一个具有类型标志的变量并分配一个值 7
例如吗?我可以这样做吗:
Now can I have a variable that has type flags and assign a value 7
for example? Can I do this:
Flags f = Flags::FLAG_1 | Flags::FLAG_2 | Flags::FLAG_3;
或
Flags f = 7;
出现这个问题是因为在枚举中我没有为 7
定义值.
This question arises because in the enum I have not defined value for 7
.
推荐答案
您需要编写自己的重载 operator|
(大概还有 operator&
等).
You need to write your own overloaded operator|
(and presumably operator&
etc.).
Flags operator|(Flags lhs, Flags rhs)
{
return static_cast<Flags>(static_cast<char>(lhs) | static_cast<char>(rhs));
}
只要值在枚举值的范围内(否则为 UB;[expr.static.cast]/p10),整数到枚举类型(范围或非范围)的转换是明确定义的.对于具有固定基础类型的枚举(这包括所有作用域枚举;[dcl.enum]/p5),枚举值的范围与基础类型([dcl.enum]/p8)的值范围相同.如果底层类型不固定,规则会更棘手 - 所以不要这样做:)
Conversion of an integer to an enumeration type (scoped or not) is well-defined as long as the value is within the range of enumeration values (and UB otherwise; [expr.static.cast]/p10). For enums with fixed underlying types (this includes all scoped enums; [dcl.enum]/p5), the range of enumeration values is the same as the range of values of the underlying type ([dcl.enum]/p8). The rules are trickier if the underlying type is not fixed - so don't do it :)
相关文章