how to do member function pointer in D?

JAnderson ask at me.com
Thu Jul 31 08:38:07 PDT 2008


u wrote:
>> I'm not sure I completely understand either but I'll take a stab.  What
>> about using polymorphism?  Where delegates can be any type of object
>> interfaces restrict what sort of objects can be used with your hash-table.
> 
> Go back to my original question:
> 
> How to create a variable which hold a particular function pointer of a class, and
> can be invoked on different objects of that class:
> 
> fp = &(A.f);
> A a1, a2;
> a1.fp();   // how to make this invocation work?
> a2.fp();
> 
> And I have one more requirement that even if A.f() and A.g() have same signature,
> 
> fp = &(A.g);   // expect compiler report error here.
> 
> How to declare the type of such fp?

//What about something like:

void funcBind(Obj, alias Func)(Obj obj)
{
    obj.Func();
}

...

alias funcBind!(A, f) fp;
A a1, a2;
fp(a1);
fp(a2);


alias funcBind!(A, g) fp;  //Compiler error -> Duplicate

//Note with a little more work you could make A implicit
//and therefore have any class Type as the first parameter.

I can't really see why function/member pointers are necessary for this 
situation since Member pointers are one to many and you seem to want a 
one-to-one relationship.


-Joel



More information about the Digitalmars-d mailing list