如何在 C++ 中使用枚举作为标志? [英] How to use enums as flags in C++?

查看:31
本文介绍了如何在 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.

这篇关于如何在 C++ 中使用枚举作为标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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