这个枚举转换有效吗?

huangapple go评论69阅读模式
英文:

Is this enum conversion valid?

问题

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

英文:

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;
}

答案1

得分: 0

是的,这被保证可以正常工作。

术语:

  • 使用 enum structenum class 声明的枚举称为 作用域枚举
  • 枚举的 底层类型 是用来表示它的整数类型
  • 每个作用域枚举类型都被认为有一个 固定的 底层类型。显式指定底层类型的非作用域枚举也有固定的底层类型。没有显式指定底层类型的非作用域枚举仍然有一个底层类型,但它不是固定的。(当枚举没有固定的底层类型时,编译器将选择一个足够大以表示所有枚举值的未指定底层类型。)

具有固定底层类型的枚举可以保存其底层类型的任何值(包括不被其枚举器之一表示的值)。它可以在不改变值的情况下转换为该底层类型,反之亦然。这由标准保证。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月21日 00:07:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定