如何使用枚举作为C ++中的标志? [英] How to use enums as flags in C++?
问题描述
通过 [Flags]
属性,处理枚举
作为标志在C#中工作得很好,但是最好的方法是什么在C ++中这样做?
例如,我想写:
enum AnimalFlags
{
HasClaws = 1,
CanFly = 2,
EatsFish = 4,
Endangered = 8
}
seahawk.flags = CanFly | EatsFish |濒危;但是,我遇到了关于 int
的编译器错误。 / 枚举
转换。有没有更好的方式来表达这不只是钝的铸造?优选地,我不想依赖于第三方库(例如boost或Qt)的构造。
编辑:如答案所示,我可以避免编译器错误通过将 seahawk.flags
声明为 int
。但是,我想有一些机制来强制类型安全,所以有人不能写 seahawk.flags = HasMaximizeButton
。
code> enum AnimalFlags
{
HasClaws = 1,
CanFly = 2,
EatsFish = 4,
Endangered = 8
}
inline AnimalFlags运算符|(AnimalFlags a,AnimalFlags b)
{return static_cast< AnimalFlags>(static_cast< int>(a)| static_cast< int>(b));}
等。其余的位运算符。如果枚举范围超出了int范围,请根据需要进行修改。
Treating enum
s as flags works nicely in C# via the [Flags]
attribute, but what's the best way to do this in C++?
For example, I'd like to write:
enum AnimalFlags
{
HasClaws = 1,
CanFly =2,
EatsFish = 4,
Endangered = 8
};
seahawk.flags = CanFly | EatsFish | Endangered;
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.
EDIT: 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));}
Etc. rest of the bit operators. Modify as needed if the enum range exceeds int range.
这篇关于如何使用枚举作为C ++中的标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文