how to do member function pointer in D?

newbie some at where.com
Wed Jul 30 11:27:28 PDT 2008


The main problem is that I want to let the D compiler check the type for me: e.g.

mfp1 = function void(A obj) { obj.f(); };
mfp2 = function void(A obj) { obj.g(); };
void function(A) fp;   // suppose fp is what I intended to call A.f()

fp = mfp1;    // cass 1: OK
fp = mfp2;    // cass 2: OK
mfp1 = mfp2;  // cass 3: also OK

Of course this is because fp is specified by the signature of it's arguments type
and return type.

I want a member function pointer type that is more strict than this, i.e. both
case (2 & 3) will cause compiler type error.

Another minor issue with your suggested approach is that: I have to write those
wrappers for all the member function that I want to use.


== Quote from Russell Lewis (webmaster at villagersonline.com)'s article
> Although people have presented hacks to do this, there isn't a standard
> way to do this in D.
> Of course, you could use a function literal to accomplish this:
>    mfp = function void(A obj) { obj.f(); };
> That isn't techically a member function pointer, but it is pretty similar.
> Do you have a compelling use case where you need member-function-pointer
> but delegates or the function literal above wouldn't work?  I haven't
> yet heard of one, but of course they might exist. :)
> Russ
> newbie wrote:
> > Hi,
> >
> > I want to be able to create a member function pointer type from a class (not
> > from an object of that class), i.e.
> >
> > class A {
> >   void f() {}
> >   void g() {}
> > }
> >
> > (member function pointer) mfp = &A.f; // what's the sytax for the type?
> >
> > // also I want the compiler to report error if I pass g() to mfp:
> > mfp = &A.g;   // type error!
> >
> > // and mfp can be invoked on different object instance of A:
> > A a1, a2;
> >
> > mfp(a1);   // call a1.f(), what's the right syntax?
> > mfp(a2);   // call a2.f()
> >
> > Thanks.




More information about the Digitalmars-d mailing list