Address of instance member function

Kirk McDonald kirklin.mcdonald at gmail.com
Sat Mar 31 11:49:11 PDT 2007


Chris Nicholson-Sauls wrote:
> Deewiant wrote:
> 
>> Jarrett Billingsley wrote:
>>  > It's a function pointer to that method.  It's actually useful -- 
>> you can
>>
>>> simulate pointer-to-members using this and delegates:
>>>
>>> class A
>>> {
>>>     int mX;
>>>
>>>     this(int x)
>>>     {
>>>         mX = x;
>>>     }
>>>
>>>     void foo(int y)
>>>     {
>>>         writefln(mX, ", ", y);
>>>     }
>>> }
>>>
>>> void main()
>>> {
>>>     scope a = new A(5);
>>>     a.foo(4);
>>>
>>>     void delegate(int) dg;
>>>     dg.funcptr = &A.foo; // <<- dah
>>>     dg.ptr = cast(void*)a;
>>
>>
>> Are there other uses? Doesn't the above essentially boil down to just:
>>
>> auto dg = &a.foo;
>>
> 
> It does, except that you could later set dg.ptr to a /different/ 
> instance.  Its utility is in late binding to instances selected by some 
> arbitrary (and possibly external) means. I'd like to see if it plays 
> well with inheritance, though.
> 
> -- Chris Nicholson-Sauls

It doesn't, really.

class Base {
     void foo() { writefln("Base"); }
}

class Derived : Base {
     void foo() { writefln("Derived"); }
}

void main() {
     void delegate() dg;
     dg.funcptr = &Base.foo;
     dg.ptr = new Derived;
     dg(); // will print "Base"
}

However, this is precisely the behavior I would expect, and in fact Pyd 
relies on it.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list