I like to use enum classes, but I use them as flags sometimes and I have to constantly cast to int if I want to use a bitwise operator. Is there a way to do this without casting? I don't think you can define the operators for them?
If I have functions that take an enum class, do I have to do this?
enum class Flags { FLAG1, FLAG2, FLAG3};
void setFlags(Flags flags){}
int main()
{
setFlags((Flags)((int)Flags::FLAG1 | (int)Flags::FLAG2 | (int)Flags::FLAG3));
}
The
classafter theenumspecifies that an enumeration is strongly typed and that its enumerators are scoped. Beware,enum classhas only assignment, initialization and comparisons defined by default. Nevertheless, an enumeration is user-defined type, as such, you can define operators for it.If you don't want to explicitly qualify enumerator names and want enumerator values to be
ints(without the need for an explicit conversion), you can remove theclassfromenum classto get "plain"enum. Enumerators are exported to the surrounding scope to evade name collisions, you can wrap with namespace.References: