I have a enum that I am trying to create operator overloads. I am struggling with the boolean comparison operator.
Here is what I have:
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));
}
So with this enum class, I can issue the statements:
LogLevel a = LogLevel::Info;
LogLevel b = LogLevel::Warning;
LogLevel c = a & b;
But I also want to do:
if( a && b) {
//do work
}
My inline operator declaration for && is not correct, but I am not sure what to change it to.
Ideas?
There's a couple of problems with your code
TraceLevel
but use LogLevel
operator&
is after your use of it in the definition of operator&&
I have renamed LogLevel
to be TraceLevel
and have moved the definition of operator&
to be before the definition of operator&&
(and as suggested in the comment removed underscores), see working example 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";
}
}
User contributions licensed under CC BY-SA 3.0