auto parameter causing template (suggestion for D)
david
davidl at 126.com
Sat Sep 23 00:02:00 PDT 2006
在 Sat, 23 Sep 2006 12:54:48 +0800,Reiner Pope
<reiner.pope at REMOVE.THIS.gmail.com> 写道:
> 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
Yeah, auto can be generalized to return type too. Good point. This way is
quite elegant. Hope we can see that in dmd 0.168 :p
--
使用 Opera 革命性的电子邮件客户程序: http://www.opera.com/mail/
More information about the Digitalmars-d
mailing list