Enum conversion

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 21 16:59:37 UTC 2020


On 4/21/20 12:03 PM, Russel Winder wrote:
> Hi,
> 
> Given an enum:
> 
> enum ZoneNumber {
>      One = 1,
>      Two = 2,
> }
> 
> then which of these is the right way of accessing the value?
> 
> cast(ubyte)ZoneNumber.One
> to!ubyte(ZoneNumber.One)

I generally do this:

ubyte(ZoneNumber.One)

> 
> conversely what is the right way of going the other way:
> 
> cast(ZoneNumber)1

This will incur zero runtime cost, so I would recommend that.

> to!ZoneNumber(1)

This works too, I think it just does the equivalent of the first, but if 
not inlined, you will incur some runtime cost.

> 
> I tried:
> 
> enum ZoneNumber : ubyte {
>      One = 1,
>      Two = 2,
> }
> 
> but the members One and Two still seem to be types as int. :-(
They are typed as ZoneNumber, which is a derivative of ubyte. What 
measurement are you doing to determine that they are int?

auto x = ZoneNumber.One;
ubyte y = x; // fine

If you leave off the :ubyte part, the declaration of y would fail.

Similarly, this would fail:

enum ZoneMember : ubyte {
    One = 1,
    Two = 2,
    ThreeThousand = 3000, //  Error: cannot implicitly convert 
expression 3000 of type int to ubyte
}

-Steve


More information about the Digitalmars-d-learn mailing list