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

后端 未结 7 1946
醉酒成梦
醉酒成梦 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:46

    struct Error {
        enum {
            None        = 0,
            Error1      = 1,
            Error2      = 2,
        } Value;
    
        /* implicit */ Error(decltype(Value) value) : Value(value) {}
    
        explicit operator bool() {
            return Value != Error::None;
        }
    };
    
    inline bool operator==(Error a, Error b) {
        return a.Value == b.Value;
    }
    
    inline bool operator!=(Error a, Error b) {
        return !(a == b);
    }
    

    enum has no overloaded operator for now, so wrap it in a class or struct.

提交回复
热议问题