strong enums: why implicit conversion to basetype?

Trass3r un at known.com
Thu Jan 26 05:59:18 PST 2012


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.


More information about the Digitalmars-d mailing list