重载枚举布尔比较?

时间:2015-02-18 22:53:43

标签: c++11 enums overloading

我有一个枚举,我正在尝试创建运算符重载。我正在努力使用布尔比较运算符。

这就是我所拥有的:

enum class TraceLevel : uint32_t {

    // Basic logging levels (may be combined with trace level)
    All = 0xFFFFFFFF,
    None = 0x00000000,
    Info = 0x00000001,
    Warning = 0x00000002,
    Error = 0x00000004,
    Logging = 0x0000000F,
};

inline bool operator&&(TraceLevel __x, TraceLevel __y) {
    return static_cast<uint32_t>(__x & __y) > 0;
}

inline constexpr TraceLevel
operator&(TraceLevel __x, TraceLevel __y) {
    return static_cast<TraceLevel>
        (static_cast<uint32_t>(__x) & static_cast<uint32_t>(__y));
}

所以使用这个枚举类,我可以发出声明:

LogLevel a = LogLevel::Info;
LogLevel b = LogLevel::Warning;

LogLevel c = a & b;

但我也想这样做:

if( a && b) {
   //do work
}

我的内联运营商声明&amp;&amp;是不对的,但我不知道该怎么改变它。

想法?

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题

  1. 您定义TraceLevel但使用LogLevel
  2. operator&的定义是在operator&&
  3. 的定义中使用之后

    我已将LogLevel重命名为TraceLevel,并已将operator&的定义移至operator&&的定义之前(并在评论中删除了下划线) ,请参阅工作示例here

    #include <iostream>
    
    enum class TraceLevel : uint32_t {
    
        // Basic logging levels (may be combined with trace level)
        All = 0xFFFFFFFF,
        None = 0x00000000,
        Info = 0x00000001,
        Warning = 0x00000002,
        Error = 0x00000004,
        Logging = 0x0000000F,
    };
    
    inline constexpr TraceLevel
    operator&(TraceLevel x, TraceLevel y) {
        return static_cast<TraceLevel>
            (static_cast<uint32_t>(x) & static_cast<uint32_t>(y));
    }
    
    inline bool operator&&(TraceLevel x, TraceLevel y) {
        return static_cast<uint32_t>(x & y) > 0;
    }
    
    int main() {
    
        TraceLevel a = TraceLevel::Info;
        TraceLevel b = TraceLevel::Warning;
    
        TraceLevel c = a & b;
    
        if( a && b) {
            std::cerr << "a && b is true\n";
        } else {
            std::cerr << "a && b is false\n";
        }
    }