auto parameter causing template (suggestion for D)

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Fri Sep 22 21:54:48 PDT 2006


david wrote:
> take a look at this:
> 
> import std.stdio;
> void myoverload(auto foo)
> {
> static if (is ( typeof(foo):int ) )
>     { writefln("int");
>     }
> else
>     static if (is ( typeof(foo):char[] ) )
>     { writefln("char[]");
>     }
> }
> void main()
> {
>  myoverload(3);
>  myoverload("asdkjf");
> }
> 
> 
> Though this is a trivial improvement to D language. but I think that 
> affect people differently in their mind. People would no longer notice 
> they are writing a template for that myoverload
> People would see that function as a normal function.
> Though that would lost the type information where we can get from void 
> myoverload(T)(T t) directly from T, I think typeof(foo) won't bother too 
> much! And it's really elegant way to implement in that way.

Yes, it's quite elegant. This suggestion is similar to mine from 'Some 
more template syntax sugar,' but yours has the advantage of an 
unambiguous syntax (since auto is a keyword, it can't be used as a 
type). Add this to type inference of return values, and you get dead 
easy templating, or compile time duck typing, in other words. (adding 
return type inference basically means that every type can be inferred, 
and typeof expressions shouldn't be needed much)

The example I posted earlier:

T sqr(T) (T x)
{
     return x*x;
}

would become

auto sqr(auto x)
{
     return x*x;
}

and the compiler would understand this to be equivalent to:

typeof(__ret) sqr(__t1) ( __t1 x)
{
     auto __ret = x * x;
     return __ret;
}

This could work very well.

Cheers,

Reiner



More information about the Digitalmars-d mailing list