strong enums: why implicit conversion to basetype?

Alvaro alvaroDotSegura at gmail.com
Thu Jan 26 14:49:40 PST 2012


El 26/01/2012 14:59, Trass3r escribió:
> I thought it'd be good to outsource this question from the other thread
> about enums as flags.
>
> Is there any merit in having implicit conversion to the basetype?
> Imo it only introduces a severe bug source and brings no advantages.

> A better example is something like
> if (b && Bla.S2) // written '&&' instead of '&' by mistake, will
> silently pass
> Heck even +,-,... work.

I kind of agree. I understand enums as a way to define "tags" or flags 
used to define things like file open mode Read, Write, ReadWrite, 
endianness BigEndian, LittleEndian, socket type Stream/Packet, etc. 
things that under the hood are represented by integer numbers but that 
don't represent *quantities*, so should not work the same way as 
integers. What is the result of subtracting or multiplying LittleEndian 
and BigEndian? Does not make sense. Bitwise operations would be OK 
because logica tags can be combined, but little more.

And this brings the question of whether implicit casting from int to 
bool is a good thing (or making any integer a valid boolean value). The 
same way, true and false are not quantities and can't be used in 
arithmetic. Even if they are internally represented as 1 and 0, they 
should not be the same thing as numbers. IMO, Java did it better in 
making them distinct. With a non-int-convertible bool your above weird 
example would not work.




More information about the Digitalmars-d mailing list