Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 899
Nir Friedman Avatar asked Jun 12 '17 20:06

Nir Friedman


People also ask

What is the point of std :: byte?

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.

Is enum class A class C++?

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 .

Is enum class a class?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

What is the advantage of using enum in C++?

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.


1 Answers

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.

like image 146
Nicol Bolas Avatar answered Oct 21 '22 23:10

Nicol Bolas