Search code examples
c++c++17stdlanguage-designstd-byte

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


std::byte is an abstraction that is supposed to provide a type safe(r) access to regions of memory in C++, starting with the new standard 17. However, it's declared this way according to http://en.cppreference.com/w/cpp/types/byte:

enum class byte : unsigned char {} ;

That is, it is an enum class without any enumerations. Since usually the purpose of enums is to provide a restricted set of enumerations, this seems a bit strange. A class with a private unsigned char member seems like the more obvious way to do this.

Why is it done this way?


Solution

  • 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.