Enum conversion

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 21 19:48:04 UTC 2020


On 4/21/20 3:00 PM, Russel Winder wrote:
> On Tue, 2020-04-21 at 12:59 -0400, Steven Schveighoffer via
> Digitalmars-d-learn wrote:
>> 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)
> 
> Hummm… I hadn't got to that one. :-)
> 
> Why choose that rather than one of the other two?

1. it's shorter and prettier.
2. No cast (I avoid using cast whenever I can).
3. No gotcha type conversions.

e.g. for point 3:

enum ZoneMember { // : int
   One = 1,
   Two = 2,
   ReallyBig = 4567,
}

auto b1 = ubyte(ZoneNumber.One); // 1 (compiler uses VRP to make this work)
auto b2 = ubyte(ZoneNumber.ReallyBig); // Compiler error

vs.

auto b1 = cast(ubyte)ZoneNumber.One; // 1
auto b2 = cast(ubyte)ZoneNumber.ReallyBig; // b2 == 215 (truncated)

vs.

auto b1 = to!ubyte(ZoneNumber.One); // 1
auto b2 = to!ubyte(ZoneNumber.ReallyBig); // runtime error

> 
> 
>>
>>> 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?
> 
> typeof(ZoneNumber.One).stringof seemed to return uint.

This is what happens for me:

enum ZoneNumber : ubyte {
   One = 1,
   Two = 2,
}

pragma(msg, typeof(ZoneNumber.One).stringof); // ZoneNumber

-Steve


More information about the Digitalmars-d-learn mailing list