strong enums: why implicit conversion to basetype?

deadalnix deadalnix at gmail.com
Thu Jan 26 10:50:58 PST 2012


Le 26/01/2012 14:59, Trass3r a écrit :
> 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!
>
> 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 don't see any problem with that : it is perfectly safe. The other way 
around isn't and isn't allowed, so the current behaviour seems fine to me.


More information about the Digitalmars-d mailing list