snippetcppCritical
How to use enums as flags in C++?
Viewed 0 times
enumsflagshowuse
Problem
Treating
For example, I'd like to write:
However, I get compiler errors regarding
EDIT: As indicated in the answers, I can avoid the compiler error by declaring
enums as flags works nicely in C# via the [Flags] attribute, but what's the best way to do this in C++?For example, I'd like to write:
enum AnimalFlags
{
HasClaws = 1,
CanFly =2,
EatsFish = 4,
Endangered = 8
};
seahawk.flags = CanFly | EatsFish | Endangered;However, I get compiler errors regarding
int/enum conversions. Is there a nicer way to express this than just blunt casting? Preferably, I don't want to rely on constructs from 3rd party libraries such as boost or Qt.EDIT: As indicated in the answers, I can avoid the compiler error by declaring
seahawk.flags as int. However, I'd like to have some mechanism to enforce type safety, so someone can't write seahawk.flags = HasMaximizeButton.Solution
The "correct" way is to define bit operators for the enum, as:
Etc. rest of the bit operators. Modify as needed if the enum range exceeds int range.
enum AnimalFlags
{
HasClaws = 1,
CanFly = 2,
EatsFish = 4,
Endangered = 8
};
inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b)
{
return static_cast(static_cast(a) | static_cast(b));
}Etc. rest of the bit operators. Modify as needed if the enum range exceeds int range.
Code Snippets
enum AnimalFlags
{
HasClaws = 1,
CanFly = 2,
EatsFish = 4,
Endangered = 8
};
inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b)
{
return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b));
}Context
Stack Overflow Q#1448396, score: 329
Revisions (0)
No revisions yet.