Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explain what "when necessary" means in Enum.7. #1977

Closed
BartVandewoestyne opened this issue Sep 30, 2022 · 4 comments
Closed

Explain what "when necessary" means in Enum.7. #1977

BartVandewoestyne opened this issue Sep 30, 2022 · 4 comments
Assignees

Comments

@BartVandewoestyne
Copy link

Enum.7 reads "Specify the underlying type of an enumeration only when necessary" but to me (and most likely others) it is not 100% clear what "when necessary" exactly means. In the code example, one comment writes "underlying type saves space" and the note in Enum.7 mentions that specifying the underlying type is necessary in forward declarations of enumerations. So my current conclusion would be that "when necessary" can mean only two things:

  1. You want to save space,
  2. You want to forward declare the enumeration.

Am I correct and are these the only two cases? Or are there other circumstances that would require specifying the underlying type to be necessary? If 'yes', then it would be nice if Enum.7 was expanded with a list of circumstances under which this is necessary.

@jwakely
Copy link
Contributor

jwakely commented Sep 30, 2022

For an unscoped enumeration type, specifying the underlying type means that all values of the underlying type are valid values of the enumeration. So this is OK:

enum X : int { x0, x1, x2 };
X x = static_cast<X>(4);

Without the underlying type that is undefined, because the only valid values are 0,1,2,3.

@beinhaerter
Copy link
Contributor

beinhaerter commented Oct 6, 2022

A case where I am specifying the underlying type is, when I have an enum that I am using in a struct for data received over a network socket. The memory layout of the data is fixed, it is part of the API. To be sure that the enum size matches the data size I am specifying std::uint8_t oder std::uint16_t for example.

@hsutter
Copy link
Contributor

hsutter commented Oct 13, 2022

Editors call: Okay, we could add "for example, specifying the underlying type is necessary to forward-declare an enum or enum class, or to ensure that values of type that can have a specified bit-precision"

@hsutter
Copy link
Contributor

hsutter commented Dec 1, 2022

Closed with PR #2000 .

@hsutter hsutter closed this as completed Dec 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants