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 枚举类用于标志


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01