how to do member function pointer in D?

BCS ao at pathlink.com
Wed Jul 30 11:36:36 PDT 2008


Reply to Newbie,

> 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.
> 

That is not something the type system can do. The two methods operate on 
the same object type, take the same args and return the same type. As far 
as the type system system is concerned, they are identical.

Maybe I'm missing something because what you seem to want doesn't seem useful 
to me, the restriction you seem to want would restrict the allowable values 
for fp to exactly one. If this is so, why do you want a variable?

The only use I can think of is if you want to call a the f method from a 
base class on an object of a derived class. If this is the case you are subverting 
the type system so you are on your own.

> 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