Why no non-integral enums?

后端 未结 4 1138
挽巷
挽巷 2021-01-18 09:20

Why is it that non-integral enums cannot be created? I want to know if this is a language design decision, or if there are issues with implementing this in the compiler.

4条回答
  •  有刺的猬
    2021-01-18 09:56

    There's no technical reason why it couldn't be done, but then, we are really more talking about a set of constants (perhaps within a common namespace, if they're related).

    In an enum, the numerical value is generally secondary.

    In the following:

    enum Fruit {
      Apple,
      Orange,
      Pear,
      Peach
    }
    

    we are only describing a set of named constants. We are saying that a variable of type Fruit can take one of these four values. What the integer value of each one is, is really not relevant. As long as I only refer to them by name, it doesn't matter if the value representing Apple is 0, 1, 32, -53 or 0.002534f.

    Most languages do allow you to specify the value that should represent each, but that's really secondary. It's sometimes useful, but it's not part of the core purpose with enums. They are simply there to give you a set of related named constants without having to specify an integer ID for each.

    Further, enums are often used to specify optional flags that can be combined with bitwise operations. That is trivial to implement if each value is represented by an integer (then you just have to pick an integer that uses the bit pattern you want). Floating-point values wouldn't be useful in this context. (bit-wise and/or operations don't make much sense on floating-point values)

提交回复
热议问题