Type deduction using switch case

Robert Jacques sandford at jhu.edu
Sat Feb 18 16:49:57 PST 2012


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.

> While static if would be more practical for templates, my idea
> could be extended to dynamic upcasting of classes as well, which
> could be applied to exception handling:
>
> try{ ... }
> catch(Throwable err) switch(err){
> 	case IOError a:
> 		break;
> 	case OutOfMemoryError b:
> 		break;
> 	default:
> 		throw err;
> }

You can do this today using a string switch:
switch(err.classinfo.name) { ... }


More information about the Digitalmars-d mailing list