Enum conversion

Russel Winder russel at winder.org.uk
Tue Apr 21 19:00:52 UTC 2020


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?


> 
> > 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.

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

Oooo… I like this, adding ":ubyte" immediately.

-- 
Russel.
===========================================
Dr Russel Winder      t: +44 20 7585 2200
41 Buckmaster Road    m: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20200421/d92df366/attachment.sig>


More information about the Digitalmars-d-learn mailing list