Newbie initial comments on D language - delegate

Russell Lewis webmaster at villagersonline.com
Tue Jan 29 08:07:23 PST 2008


Yeah, I've seen people use the union magic to make it work without a 
new.  It's a cool trick, but it makes me squirm when I think about 
portability.  So I use a general version, using closures (note that my 
template uses a fixed "void" return code...previous posts in the NG can 
show you how to IFTI non-void return codes):

void delegate(TPL) convert(TPL...)(void function(TPL) func)
{
   return delegate void(TPL args)
          {
            func(args);
          };
}

// note that 'func' is put on the heap automatically by the closure
// mechanism in the compiler.

BCS wrote:
> Reply to Russell,
> 
>> what I did was just generate a template which automatically created a
>> delegate out of it.
>>
> 
> somthing like this?
> 
> // IFTI might want somthing else\ here
> R delegate(A) convert(R, A...)(R function(A) fnp)
> {
>  struct S
>  {
>      // "this" is a function pointer not a S*
>     R do(A a) { U u; u.s = this; retrun s.f(a);}
>  }
> 
>  union U
>  {
>     S* s;
>     R function(a) f;
>  }
> 
>  U u;
>  u.f= fnp;
>  retrun &u.s.do;
> }
> 
> note it never news anything!
> 
> *Untested, but I've used the idea befor.*
> 
> 



More information about the Digitalmars-d mailing list