Function to delegate conversion

Kirk McDonald kirklin.mcdonald at gmail.com
Mon Jun 26 13:49:26 PDT 2006


Kirk McDonald wrote:
> For instance:
> 
> class A {
>     void foo() { }
> }
> 
> void main() {
>     A a = new A;
>     void function() fn = &A.foo;
> }
> 
> Without the ability to convert fn into a delegate to a.foo, implementing 
> this class-wrapping functionality is all but impossible.
> 

The following dirty, dirty hack /appears/ to work, at least in this 
trivial case:

import std.stdio;

struct DG {
     Object instance;
     void function() fn;
}

union U {
     DG fake_dg;
     void delegate() real_dg;
}

class A {
     void foo() { writefln("A.foo()"); }
}

void main() {
     A a = new A;
     void function() fn = &A.foo;

     U u;
     u.fake_dg.instance = a;
     u.fake_dg.fn = fn;

     // Call it
     u.real_dg();
}

This can be templatized into a more general solution. However, I am 
worried about how this scales (for functions with more arguments, etc), 
and of course about the fact that it is not cross-platform /at all/.

I now this subject has come up before, but I feel it is important enough 
to bring up again.

-Kirk McDonald



More information about the Digitalmars-d mailing list