C++ 中的位标志枚举

发布于 2024-08-10 13:57:52 字数 372 浏览 5 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

半步萧音过轻尘 2024-08-17 13:57:52

运行时对正确性的影响?不 - 这应该正是您想要的。

运行时对速度的影响?我希望任何像样的编译器都能正确地优化它,以减少发布版本的指令数量(尽管您可能想添加内联以确保确定)。

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).

〃温暖了心ぐ 2024-08-17 13:57:52

它可能会执行三个副本和一个函数调用,除非 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.

层林尽染 2024-08-17 13:57:52

代码是正确的。

代码的速度与没有类型转换时的速度相同。

但代码是否快并不重要,因为名为“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.

勿忘初心 2024-08-17 13:57:52

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

use std::bitset for your bit flags... much simpler ;)
or boost::dynamic_bitset.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文