How is casting to int a problem if the enum is defined to use int as the underlying type?
What if the underlying type is not an int?
I am confused. My post was a comment on the post right above it, which showed some code which specified int as the underlying type and then used a cast to int.
I do like BitMaster's code, though, despite how verbose it is. Instead of overloading any operators, I would prefer to provide a function to test if some bits are active. That function can be a template so it works for all enum types automatically (a feature that was requested by The King2), and then you have to add `typename', making the code even uglier.
#include <iostream>
#include <type_traits>
enum class WindowBorders
: unsigned char {
None = 0x00,
Left = 0x01,
Right = 0x02,
Bottom = 0x04,
LeftBottom = 0x05,
RightBottom = 0x06,
};
// Returns whether the bits set in x contain the bits set in y
template <typename T>
bool contains_bits(T x, T y) {
return (static_cast<typename std::underlying_type<T>::type>(x)
& static_cast<typename std::underlying_type<T>::type>(y))
== static_cast<typename std::underlying_type<T>::type>(y);
}
int main() {
WindowBorders wb = WindowBorders::LeftBottom;
if (contains_bits(wb, WindowBorders::Left))
std::cout << "Yay!\n";
}