Type deduction using switch case

Xinok xinok at live.com
Sat Feb 18 18:03:51 PST 2012

On Sunday, 19 February 2012 at 00:49:56 UTC, Robert Jacques wrote:
> On Sat, 18 Feb 2012 18:33:01 -0600, Xinok <xinok at live.com> 
> wrote:
>> While reading "The Right Approach to Exceptions", it gave me 
>> this
>> idea. The user would declare a list of variables of different
>> types as case statements, and the variable with matches the 
>> type
>> of the switch expression is used.
>> I don't know how the syntax should look, this is merely an
>> example:
>> void foo(T)(T arg){
>> 	switch(arg){
>> 		case int i:
>> 			writeln("Type is int ", i); break;
>> 		case float f:
>> 			writeln("Type is float ", f); break;
>> 		case string s:
>> 			writeln("Type is string ", s); break;
>> 		default:
>> 			writeln("Type is unknown"); break;
>> 	}
>> }
> The above should be switch (T) not switch(arg) for the example 
> to be correct.

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.

More information about the Digitalmars-d mailing list