Type safe enum bit flags

前端 未结 5 656
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 12:32

I\'m looking to use a set of bit flags for my current issue. These flags are (nicely) defined as part of an enum, however I understand that when you OR

5条回答
  •  清歌不尽
    2021-01-11 13:20

    The values of your constants are not closed under OR. In other words, it's possible that the result of an OR of two ENUM constants will result in a value that is not an ENUM constant:

    0x30 == FIVE | SIX;
    

    The standard says that this is ok, an enumaration can have a value not equal to any of its enumarators (constants). Presumably it's to allow this type of usage.

    In my opinion this is not type safe because if you were to look at the implementation of enumTest you have to be aware that the argument type is ENUM but it might have a value that's not an ENUM enumerator.

    I think that if these are simply bit flags then do what the compiler wants you to: use an int for the combination of flags.

提交回复
热议问题