Is it possible to convert a delegate into a function?

Chris Williams yoreanon-chrisw at yahoo.co.jp
Thu Feb 6 15:11:45 PST 2014


On Thursday, 6 February 2014 at 22:15:00 UTC, Dicebot wrote:
> 	assert(!dg.ptr);

Note that Dicebot's version works only because he chose a 
delegate that points to something that doesn't need an external 
state. The below method, Foo.dump(), would fail the assert 
because it requires a reference to an instance of Foo in order to 
grab the state of a.value or b.value.

It does look like one is allowed to write into the delegate .ptr 
and .funcptr variables, so reconstructing a delegate from parts 
is possible. (I'm surprised that the definition of funcptr is 
"void function()" instead of "void function(Foo)"?).


import std.stdio;

class Foo {
private:
     int value;

public:
     this(int v) {
         value = v;
     }

     void dump() {
         writeln(value);
     }
}

void doDump(void* obj, void function() func) {
     void delegate() dg;
     dg.ptr = obj;
     dg.funcptr = func;
     dg();
}

void main() {
     Foo a = new Foo(42);
     Foo b = new Foo(255);

     auto dgA = &a.dump;
     auto dgB = &b.dump;

     writefln("%x %x", dgA.funcptr, dgB.funcptr); // Same

     void function() func = dgA.funcptr;

     doDump(dgA.ptr, func);
     doDump(dgB.ptr, func);
}


More information about the Digitalmars-d-learn mailing list