Bitflag enums in C++

送分小仙女□ 提交于 2019-12-10 23:34:54

问题


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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/1693579/bitflag-enums-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!