如何在 C++ 中使用枚举作为标志?

2021-12-29 00:00:00 enums c++

通过 [Flags] 属性在 C# 中将 enums 视为标志可以很好地工作,但是在 C++ 中这样做的最佳方法是什么?

Treating enums as flags works nicely in C# via the [Flags] attribute, but what's the best way to do this in C++?

例如,我想写:

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};

seahawk.flags = CanFly | EatsFish | Endangered;

但是,我收到有关 int/enum 转换的编译器错误.有没有比直接投射更好的方式来表达这一点?最好,我不想依赖来自 3rd 方库(例如 boost 或 Qt)的构造.

However, I get compiler errors regarding int/enum conversions. Is there a nicer way to express this than just blunt casting? Preferably, I don't want to rely on constructs from 3rd party libraries such as boost or Qt.

如答案所示,我可以通过将 seahawk.flags 声明为 int 来避免编译器错误.但是,我想有一些机制来强制执行类型安全,所以有人不能写 seahawk.flags = HasMaximizeButton.

As indicated in the answers, I can avoid the compiler error by declaring seahawk.flags as int. However, I'd like to have some mechanism to enforce type safety, so someone can't write seahawk.flags = HasMaximizeButton.

推荐答案

正确"的方式是为枚举定义位运算符,如:

The "correct" way is to define bit operators for the enum, as:

enum AnimalFlags
{
    HasClaws   = 1,
    CanFly     = 2,
    EatsFish   = 4,
    Endangered = 8
};

inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b)
{
    return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b));
}

等等.其余的位运算符.如果 enum 范围超过 int 范围,则根据需要进行修改.

Etc. rest of the bit operators. Modify as needed if the enum range exceeds int range.

相关文章