0

In this code below, is the conversion in function fn guaranteed to get the u64 value back, for all possible u64 values? The use for this conversion from int->enum and back is to trigger overload resolution to choose a particular int function.

using u64 = unsigned long; // 64bits

enum class EnumT : u64 {};

void Fn(u64 v) {/*...*/}

void Fn(EnumT e) {
    u64 v = u64(e);  
    // ...
}

int main() {
    u64 e = 1337;
    Fn(EnumT(e));
    return 0;
}
Dess
  • 2,064
  • 19
  • 35
  • Out of curiosity, why define `u64` instead of using `std::uint64_t`? – Brian61354270 Mar 20 '23 at 16:09
  • 1
    The comment by @Brian61354270 has some contradiction. It says that it's UB. But, based on the linked answer, it seems to be defined behavior because the enum has fixed u64 size and the converted values are of type u64. – Dess Mar 20 '23 at 16:38
  • Related: [What happens if you static_cast invalid value to enum class?](https://stackoverflow.com/q/18195312/11082165) – Brian61354270 Mar 20 '23 at 16:52
  • Whoops, you're right. I deleted that comment so as to not misinform. – Brian61354270 Mar 20 '23 at 16:53

1 Answers1

0

Yes, this is guaranteed to work correctly.

Terminology:

  • An enum declared using enum struct or enum class is said to be a scoped enumeration
  • The underlying type of an enumeration is the integer type that is used to represent it
  • Every scoped enumeration type is said to have a fixed underlying type. Unscoped enumerations that explicitly specify an underlying type also have a fixed underlying type. Unscoped enumerations that don't explicitly specify an underlying type still have an underlying type, but it is not fixed. (When an enum doesn't have a fixed underlying type, the compiler will pick an unspecified underlying type that is large enough to represent all enumerator values.)

An enumeration that has a fixed underlying type can hold any value of its underlying type (including a value that is not represented by any of its enumerators). It may be converted to that underlying type and vice versa with no change in value. This is guaranteed by the standard.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312