strange template syntax

Robert Clipsham robert at octarineparrot.com
Sun Apr 11 08:01:44 PDT 2010


On 11/04/10 15:48, Philippe Sigaud wrote:
> Hello,
>
> some time ago, chris (ruunhb) posted something on his Dspec project, where he
> used a template syntax I didn't know:
>
> ----
> void each(alias array, T : T[] = typeof(array))(void delegate(T item) dg) {
>   foreach(T i; array)
>     dg(i);
> }
>
>   int[] array = [1, 2, 3, 4];
>   int b = 10;
>
>   each!(array) = (int item) {
>     writefln("%d", item + b);
>   };
> ---
>
> I'm intrigued by the last lines. I'd have thought 'each' to be invoked by:
>
> each!(array)( (int item) {writefln("%d", item+b)} );
>
> But this doesn't work. And I never encountered Chris' syntax before:
>
> template!(someArgs) = moreArgs;
>
> Could some be nice enough to enlighten me? How does that work?
>
>
> Philippe

When using your method, you have to use:
----
each!(array, typeof(array))((int item) {writefln("%d", item+b)});
----
(I believe this is a bug, dmd should be able to deduce the type here). 
As for the syntax, you can do this with any function in D:
----
void foo(int a) { writefln( "%d", a ); }
/// Prints 1
foo = 1;
----
I didn't realize this worked for free functions, apparently it does. I 
think in newer versions of D2 functions like this will have to be marked 
with @property, I don't think dmd currently enforces this though.


More information about the Digitalmars-d-learn mailing list