The definition of templates in D

FeepingCreature default_357-line at yahoo.de
Sun Mar 18 03:40:10 PDT 2012


On 03/18/12 11:39, FeepingCreature wrote:
> On 03/18/12 11:36, FeepingCreature wrote:
>> On 03/18/12 11:29, Derek wrote:
>>> On Sun, 18 Mar 2012 19:16:02 +1100, Andrej Mitrovic <andrej.mitrovich at gmail.com> wrote:
>>>
>>>> On 3/18/12, Derek <ddparnell at bigpond.com> wrote:
>>>>> What would be useful is ...
>>>>>   bar!(a, b, c); // is equivalent to
>>>>>   bar!(int, int, int).bar(a, b, c);
>>>>
>>>> You mean like this?
>>>>
>>>> template bar(T...)
>>>> {
>>>>     void bar() { writeln(T); }
>>>> }
>>>>
>>>> void main()
>>>> {
>>>>     int a = 1, b = 2, c = 3;
>>>>     bar!(a, b, c);
>>>> }
>>>
>>> Almost, but more like this ...
>>>
>>> template add(X,Y,Z)
>>> {
>>>    X add(Y a, Z b)
>>>    {
>>>        return cast(X) (cast(X)a + cast(X)b);
>>>    }
>>> }
>>>
>>> void main()
>>> {
>>>      double s;
>>>      int   t;
>>>      ulong u;
>>>
>>>      s = 1.23;
>>>      t = 123;
>>>      u = 456;
>>>
>>>     t = add!(u,s);
>>>
>>>     writefln( "%s %s %s", s,t, u );
>>> }
>>>
>>>
>>>
>>> This currently errors with ...
>>>
>>>   "Error: template instance add!(u,s) add!(u,s) does not match template declaration add(X,Y,Z)"
>>>
>> why would you do that
>>
>> what do you want to _do_
>>
>> it sounds like you're frantically trying to nail templates into a shape that they really really really aren't meant for
>>
>> in any case what is wrong with auto add(T)(T t) { return t[0] + t[1]; }
> 
> oh
> 
> you may have misunderstood me
> 
> a template is a **compile time parameterized namespace**
> 
> its parameters are **types** and **constants**, not runtime values
> 
> "add" is a "namespace that is instantiated with the types float and"
> 
> OOOOOOOOOOOOOOOOOOOOH
> I get what you want. :D
> 
> template add(T) {
>   template add(U...) {
>     auto add(U u) {
>       T res;
>       foreach (value; u) res += value;
>       return res;
>     }
>   }
> }
> 
> void main()
> {
>      double s;
>      int   t;
>      ulong u;
> 
>      s = 1.23;
>      t = 123;
>      u = 456;
> 
>      t = add!int(u, s);
> 
>     writefln( "%s %s %s", s, t, u );
> }

which of course doesn't work because you can't add a double to an int.

So .. maybe I don't get what you want.


More information about the Digitalmars-d mailing list