Type deduction using switch case

Robert Jacques sandford at jhu.edu
Sat Feb 18 22:28:38 PST 2012


On Sat, 18 Feb 2012 20:03:51 -0600, Xinok <xinok at live.com> wrote:

> 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.
>

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;
  	}
  }


More information about the Digitalmars-d mailing list