重载枚举布尔比较?

Overloading enum boolean comparison?

我有一个正在尝试创建运算符重载的枚举。我正在与布尔比较运算符作斗争。

这是我的资料:

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));
}

所以有了这个枚举 class,我可以发出语句:

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

LogLevel c = a & b;

但我也想做:

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

我对 && 的内联运算符声明不正确,但我不确定要将其更改为什么。

想法?

你的代码有几个问题

  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";
    }
}