Type deduction using switch case

Xinok xinok at live.com
Sun Feb 19 09:02:50 PST 2012


On Sunday, 19 February 2012 at 06:28:37 UTC, Robert Jacques wrote:
> On Sat, 18 Feb 2012 20:03:51 -0600, Xinok <xinok at live.com> 
> wrote:
>> Notice how it's "int i" and not just "int". Also notice how 
>> each
>> writeln statement also prints the variable. Each case statement
>> declares a variable, so it matches the type of the expression
>> against the type of the variable, and stores the switch
>> expression in that variable.
>>
>
> And why not simply do:
>
>  void foo(T)(T arg){
>      switch(T){
>  		case int:
>  			writeln("Type is int ", arg); break;
>  		case float:
>  			writeln("Type is float ", arg); break;
>  		case string:
>  			writeln("Type is string ", arg); break;
>  		default:
>  			writeln("Type is unknown"); break;
>  	}
>  }
Because all of the code gets compiled in, so if one statement 
uses the type incorrectly, it won't compile. It also doesn't 
allow for dynamic upcasting of classes as in my second example.


More information about the Digitalmars-d mailing list