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?
std::byte is a distinct type that implements the concept of byte as specified in the C++ language definition. Like char and unsigned char, it can be used to access raw memory occupied by other objects (object representation), but unlike those types, it is not a character type and is not an arithmetic type.
enum class is not a class definition - the combination of keywords is used to define a scoped enumeration, which is a completely separate entity from a class .
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
Advantages of Enum Data TypesEnum is constant rather than being a number, it helps in increasing the source code readability. Enum also forces you to think about all the maximum possible values an enumerator can take in codes. Enum always restricts the values an enum variable can take in programming.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With