如何将C ++ 11枚举类用于标志 [英] How to use C++11 enum class for flags

查看:96
本文介绍了如何将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枚举类用于标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆