Type safe enum bit flags

前端 未结 5 617
佛祖请我去吃肉
佛祖请我去吃肉 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:23

    With a simple enum such as yours:

    enum ENUM
    {
        ONE     = 0x01,
        TWO     = 0x02,
        ...
    };
    

    it is implementation-defined what's the underlying type (most likely int)1, but as long as you are going to use | (bitwise or) for creating masks, the result will never require a wider type than the largest value from this enum.


    [1] "The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int."

提交回复
热议问题