strong enums: why implicit conversion to basetype?
Timon Gehr
timon.gehr at gmx.ch
Thu Jan 26 09:29:00 PST 2012
On 01/26/2012 02:59 PM, Trass3r wrote:
> 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.
>
> For example it allows implicit conversion to bool.
>
> enum Bla
> {
> S1 = 1,
> S2,
> S3
> }
> if (Bla.S2) // makes no sense at all, all Blas convert to true
> // and if S1 was 0, it would mean false, but it isn't meant as a special
> member!
That is not an implicit conversion. if(x) is equivalent to if(cast(bool)x).
>
> A better example is something like
> if (b && Bla.S2) // written '&&' instead of '&' by mistake, will
> silently pass
>
>
> In general it allows operations that don't make any sense.
>
> if (Bla.S2 & Blub.S1) // works cause an int is produced
> // but by using named enums I made clear that Bla and Blub are totally
> different
>
> Heck even +,-,... work.
>
> Remember that if you do need to do such crazy stuff you can still
> explicitly cast to int or whatever.
I have argued for banning those operations on strong enums before, but
some objected to it because they wanted to use strong enums as bit flags.
More information about the Digitalmars-d
mailing list