A safer switch? + abbreviation of member names in enum switches

Ellery Newcomer ellery-newcomer at utulsa.edu
Mon Oct 12 13:24:01 PDT 2009


Justin Johansson wrote:
> Speaking of switch statements, when switching on an enum type, e.g.
> 
> enum Color {
>    RED,
>    GREEN,
>    BLUE
> }
> 
> void foo( Color color) {
>    switch (color) {
>    case Color.RED:
>       break;
>    case Color.GREEN:
>       break;
>    case Color.BLUE:
>       break;
>    }
> }
> 
> Would it be possible for the compiler to infer the declared enum type, in this case Color, making for abbreviation of the enum member names in the case clauses as per the following?
> 
> void bar( Color color) {
>    switch (color) {
>    case RED:
>       break;
>    case GREEN:
>       break;
>    case BLUE:
>       break;
>    }
> }
> 
> 
> Koala hugs,
> 
> -- Justin Johansson
> 

I bet if you modified parse.c to translate

switch(x){

...

   case Exp:

...

}

to

switch(x){

...

   static if(is(typeof(x) == enum)){ with(typeof(x)){case Exp:}}
   else {case Exp:}

...

}

you could have your cake.

Can anyone see any potential problems with this (other than symbol
shadowing)?

Pipsissewa hugs



More information about the Digitalmars-d mailing list