Why is std::byte an enum class instead of a class?

A class with an unsigned char member would not be required by the standard to be the same size or alignment as unsigned char. Whereas the standard requires that enumerations be the same size and alignment as their underlying types.

Now, the standard could have simply declared that it is a class type with no standard-defined member, but with specific requirements on its size, alignment, constexpr constructors, etc; implementations would have to follow through on those expectations. But it’s much easier to simply use enum class to get the same effect. You get all of the constructors and conversion behavior that you’d expect. And since enum class types are treated as different types than their underlying type, you get all of the behavior you want with no real downside to defining it this way.

Leave a Comment

tech