D doesn't have real closures

0ffh spam at frankhirsch.net
Tue Sep 11 11:25:23 PDT 2007


Brad Anderson wrote:
> http://www.hans-eric.com/2007/09/11/d-doesnt-have-real-closures/
> 
> Please digg and reddit.
> 
> BA

You want multicast?

Well, for multicast functions (with one parameter) it seems to be
rather straightforward template programming:

---<snip>---
module multicastFunctions;

template mcf(T)
{
   class mcf
   {
     void function(T) fun;
     mcf next;

     void opCall(T x)
     {
       fun(x);
       if (next !is null)
         next(x);
     }

     mcf opCat(mcf n)
     {
       mcf m=this.dup();
       m.next=n.dup();
       return m;
     }

     mcf dup()
     {
       return new mcf(this);
     }

     this(mcf m)
     {
       this(m.fun,m.next);
     }

     this(void function(T) d,mcf n=null)
     {
       fun=d;
       next=n;
     }
   }
}

void fa(int x)
{
   printf("fa(%i)\n",x);
}

void fb(int x)
{
   printf("fb(%i)\n",x);
}

void main()
{
   mcf!(int) a=new mcf!(int)(&fa);
   mcf!(int) b=new mcf!(int)(&fb);
   mcf!(int) c=a~b;
   a(1);
   b(2);
   c(3);
}
---<snap>---

I am sure with all the templating wizzards floating around here
someone can come up with something that is not quite as full of
crap as my little proof of concept code, probably with multiple
parameter feature and whatnot; dirty and obvious hack for multi
parm would be to have N copies of the template for 0..N-1 parms.

Look ma, no C#!

Regards, Frank



More information about the Digitalmars-d-announce mailing list