Advertisement
Advanced C++, Enums & Enum Classes

How do you implement type-safe bit flags with enum class?

Short answer

Using enum class with power-of-two values gives type safety but loses the built-in bitwise operators (no implicit int conversion). You restore them by overloading operator| , operator& , etc., for the enum, keeping flag combinations type-safe.

Save C++ mock interview
Advertisement
AModel answer
Using enum class with power-of-two values gives type safety but loses the built-in bitwise operators (no implicit int conversion). You restore them by overloading operator| , operator& , etc., for the enum, keeping flag combinations type-safe. Libraries or a small macro/helper template are often used to generate these operators.
enum class Perm : unsigned { R=1, W=2, X=4 };
constexpr Perm operator|(Perm a, Perm b){
    return Perm(unsigned(a)|unsigned(b));
}
Real-world example
File permissions use an enum class with overloaded bitwise operators for safe flag combinations.
Likely follow-ups
  • Why do you need to overload operators? | How do you test a flag?
Related topics