Bitflag枚举在C ++中 [英] Bitflag enums in C++

查看:233
本文介绍了Bitflag枚举在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用枚举在C ++中存储bitflags是有点麻烦,因为一旦枚举值是ORed,它们会丢失它们的枚举类型,这会在没有显式转换的情况下导致错误。



此问题的接受答案表明,重载 | 运算符:

  FlagsSet运算符|(FlagsSet a,FlagsSet b) 
{
return FlagsSet(int(a)| int(b));
}

我想知道这个方法是否有任何运行时问题?

解决方案

正确性的运行时问题?否 - 这应该是你想要的。



速度方面的运行时影响?我希望任何体面的编译器可以适当地优化这一点,以便发布版本的最少数量的指令(尽管您可能想添加 inline 只是为了确保) p>

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?

解决方案

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

这篇关于Bitflag枚举在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆