How to use C++11 enum class for flags(如何将 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 :)
这篇关于如何将 C++11 枚举类用于标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 C++11 枚举类用于标志
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
