template magic

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 25 07:49:43 PST 2011

On Tue, 25 Jan 2011 10:21:29 -0500, spir <denis.spir at gmail.com> wrote:

> Hello,
> This post is about the various roles D templates can play. I had to  
> write a higher-order function (hof) that takes as parameter a func which  
> itself returns any kind of type. Thus, the hof is also templated. (Below  
> the simplest case I could find as example.)


> Can you believe all of those versions work fine? See whole test code  
> below.
> Now, 3 questions?
> 1. Is the fact that we have so many ways to define the same thing a Good  
> Thing, according to you?
> 2. What is the reason for Phobos defining param funcs as template  
> params? Efficiency? Why?
> 3. What is the meaning of 'alias f'? How does it work? This is a totally  
> enigmatic feature for me. Seems it allows placing anything of any type  
> as template param. Far more versatile than common use of templates as  
> 'simple' generics. Note that if I remove the seemingly useless 'alias'  
> from version 1 , I get:
>      Error: template instance hof1!(int,f) does not match template  
> declaration hof1(P,f)
> ???
> (could not find any explanation on alias params anywhere -- pointers  
> also welcome)

Your confusion probably stems from your lack of test cases :)

aliases work as any definable symbol -- template (even uninstantiated  
ones!), function, delegate, symbol, struct, variable, etc.

For instance, this also works (using your already-defined hof3)!

void main()
     int n;
     struct S
         this(int step) {this.step = step;}
         int step;
         int opCall() {return (n = (n + step));}

     S s = S(1); // step of 1
     S s2 = S(2); // step of 2

     auto intarr = hof3!s(5); // returns [1,2,3,4,5]
     auto intarr2 = hof3!s2(5); // returns [7,9,11,13,15]

Note how the alias maps to a *specific local variable* at compile-time,  
now that's kick ass.  Alias is the coolest part of templates I've seen in  
D.  It works for just about anything.

What I'd say is to make your template definition "correct" is to add some  
constraints to ensure the functor (the alias parameter) is a callable type.

auto hof3(alias f)(uint n) if (isCallable!f)


More information about the Digitalmars-d-learn mailing list