Automatic typing

John Colvin john.loughran.colvin at gmail.com
Mon Jul 1 09:45:14 PDT 2013


On Monday, 1 July 2013 at 16:33:56 UTC, Ary Borenszweig wrote:
>
> I'll give you an example:
>
> # var can be an Int or String
> def foo(var)
>   var = var.to_s
>   # do something with var, which is now guaranteed to be a 
> string
> end
>
> I can call it like this:
>
> foo(1)
> foo("hello")
>
> If I had to put types, I would end up doing of of these:
>
> 1.
>
> void foo(int var) {
>   foo(to!string(var))
> }
>
> void foo(string var) {
>   // do something with var
> }
>
> 2.
>
> void foo(T)(T var) {
>   string myVar;
>   static if (is(T == string)) {
>     myVar = var;
>   } else if (is(T == int)) {
>     myVar = to!string(var)
>   } else {
>     static assert(false);
>   }
>   // do something with myVar
> }
>

Why not this?
void foo(T)(T var)
{
     auto myVar = var.to!string;
     //do something with myVar string
}


More information about the Digitalmars-d mailing list