Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use std::byte as the underlying type for an enum class?

Tags:

c++

c++17

Since std::byte is by definition not an integral type, the following fragment is ill-formed:

enum class foo : std::byte
{
    bar = 1,
    baz = 2
};

Is there a way in C++17 to do something equivalent to this?

Edit: I'm not trying to solve any particular problem. Obviously enum class whatever : unsigned char would do it. However, I was expecting std::byte to be a little more flexible and wanted to know whether this is possible at all.

like image 904
3442 Avatar asked Dec 12 '17 23:12

3442


People also ask

What is the underlying type of an enum?

Each enum type has a corresponding integral type called the underlying type of the enum type. This underlying type shall be able to represent all the enumerator values defined in the enumeration. If the enum_base is present, it explicitly declares the underlying type.

What is enum underlying type in C++?

The type of a C++ enum is the enum itself. Its range is rather arbitrary, but in practical terms, its underlying type is an int . It is implicitly cast to int wherever it's used, though.

What is the default underlying type of each element in an enum?

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. Enums are enumerated data type in C#.

Which of the following data type can be used with enum?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.


2 Answers

std::byte is defined by the standard to be an enum class. Therefore, it has an underlying type (of unsigned char). So you can create an enum with the same underlying type:

enum class foo : std::underlying_type_t<std::byte>
{...};
like image 133
Nicol Bolas Avatar answered Sep 29 '22 13:09

Nicol Bolas


You can use unsigned char or uint8_t instead.

like image 21
Eyal Cinamon Avatar answered Sep 29 '22 14:09

Eyal Cinamon