C++ 中的位标志枚举
在 C++ 中使用枚举来存储位标志有点麻烦,因为一旦枚举值进行 OR 运算,它们就会丢失其枚举类型,这会在没有显式转换的情况下导致错误。
这个问题的可接受答案建议重载 < code>| 运算符:
FlagsSet operator|(FlagsSet a, FlagsSet b)
{
return FlagsSet(int(a) | int(b));
}
我想知道此方法是否有任何运行时影响?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
运行时对正确性的影响?不 - 这应该正是您想要的。
运行时对速度的影响?我希望任何像样的编译器都能正确地优化它,以减少发布版本的指令数量(尽管您可能想添加内联以确保确定)。
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).它可能会执行三个副本和一个函数调用,除非 RVO、寄存器和/或内联优化。
裸位或运算本身通常分解为单个处理器指令。
It potentially does three copies and a function call, barring RVO, registers, and/or inlining optimizations.
Naked bitwise OR operations themselves usually decompose to a single processor instruction.
代码是正确的。
代码的速度与没有类型转换时的速度相同。
但代码是否快并不重要,因为名为“FlagSet”的类型很可能会在条件测试的上下文中使用(->“if (Flag)”),这对速度的影响更大。寄存器大小的两个值的明智“或”。
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.
使用 std::bitset 作为您的位标志...更简单;)
或 boost::dynamic_bitset。
use std::bitset for your bit flags... much simpler ;)
or boost::dynamic_bitset.