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
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)) {
/// ...
}