简体   繁体   English

C ++中的Bitflag枚举

[英]Bitflag enums in C++

Using enums for storing bitflags in C++ is a bit troublesome, since once the enum values are ORed they loose their enum-type, which causes errors without explicit casting. 在C ++中使用枚举存储位标志有点麻烦,因为一旦对枚举值进行“或”运算,它们将失去其枚举类型,这会导致错误而没有显式转换。

The accepted answer for this question suggests overloading the | 问题的可接受答案表明| operator: 运营商:

FlagsSet operator|(FlagsSet a, FlagsSet b) 
{ 
    return FlagsSet(int(a) | int(b)); 
}

I'd like to know if this method has any runtime implications? 我想知道此方法是否对运行时有影响吗?

Runtime implications in terms of correctness? 就正确性而言,对运行时有影响吗? No - this should be exactly what you want. 不-这应该正是您想要的。

Runtime implications in terms of speed? 在速度方面对运行时有影响吗? I would expect any decent compiler to optimize this away properly to the minimal number of instructions for a release build (although you might want to add inline just to be sure). 我希望任何不错的编译器都能将其适当地优化为发行版本的最少指令数(尽管为确保确定,您可能希望添加inline )。

It potentially does three copies and a function call, barring RVO, registers, and/or inlining optimizations. 它可能会执行三个副本和一个函数调用,禁止RVO,寄存器和/或内联优化。

Naked bitwise OR operations themselves usually decompose to a single processor instruction. 裸露的按位OR操作本身通常分解为单个处理器指令。

The code is correct. 代码正确。

The code will be the same speed as without type casts. 代码的速度将与没有类型转换时的速度相同。

But whether the code is fast is irrelevant, because a type named 'FlagSet' will most probably be used in a context of conditionals test (-> "if (Flag)"), which is more of a hit to speed than a bit wise 'or' of two values of the size of a register. 但是代码是否快速无关紧要,因为名为'FlagSet'的类型很可能会在条件测试的上下文中使用(->“ if(Flag)”),这对速度的影响更大,而不是明智的选择寄存器大小的两个值的“或”。

使用std :: bitset作为您的位标志...更简单;)或boost :: dynamic_bitset。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM