How can I use an enum class in a boolean context?

后端 未结 7 1899
醉酒成梦
醉酒成梦 2021-01-07 15:59

I have some generic code that works with flags specified using C++11 enum class types. At one step, I\'d like to know if any of the bits in the flag are set. Cu

7条回答
  •  清酒与你
    2021-01-07 16:53

    I usually overload the unary + operator for flag-like enum classes, so that i can do the following:

    #define ENUM_FLAGS (FlagType, UnderlyingType)                           \
        /* ... */                                                           \
        UnderlyingType operator+(const FlagType &flags) {                   \
              return static_cast(flags)                     \
        }                                                                   \
        /* ... */                                                           \
        FlagType operator&(const FlagType &lhs, const FlagType &rhs) {      \
              return static_cast(+lhs & +rhs)                     \
        }                                                                   \
        /* ... */                                                           \
        FlagType &operator|=(FlagType &lhs, const FlagType &rhs) {          \
              return lhs = static_cast(+lhs | +rhs)               \
        }                                                                   \
        /* ... */                                                           \
        /***/
    
    // ....
    
    enum class Flags: std::uint16_t {
        NoFlag  = 0x0000,
        OneFlag = 0x0001,
        TwoFlag = 0x0002,
        // ....      
        LastFlag = 0x8000
    };
    
    ENUM_FLAGS(Flags, std::uint16_t)
    
    auto flagVar = Flags::NoFlag;
    
    // ...
    
    flagVar |= Flags::OneFlag;
    
    // ...
    
    if (+(flagVar & Flags::OneFlag)) {
        /// ...
    }
    

提交回复
热议问题