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

2023-08-26C/C++开发问题
0

本文介绍了如何在 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++ 中使用枚举作为标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6