Member function pointers

Michel Fortin michel.fortin at michelf.ca
Mon Jun 10 05:32:37 PDT 2013


On 2013-06-10 08:04:43 +0000, Jacob Carlborg <doob at me.com> said:

> On 2013-06-10 09:23, Manu wrote:
> 
>> That seems pretty awkward to me. Basically a hack.
>> A function pointer is not a delegate, so I don't see why that should be
>> used to describe one.
> 
> It depends on how you look at it. In D a delegate is a function pointer 
> with a context pointer. In C++ a pointer to a member function is 
> basically the same, the context pointer is just passed separately.

But a true member function pointer is also parametrized on the type of 
this, unlike a delegate, letting you change the object pointer in a 
type-safe manner.

(And implementation-wise, C++ function pointers can be really 
complicated beasts in order to support virtual calling and 
multiple/virtual inheritance. sizeof can even change depending on the 
type of "this". That's not what you want in D.)

>> I haven't needed to yet... but that doesn't mean it might not be useful.
>> It would probably be used in D for tight binding with other systems.
>> AngelScript binds to native code with member function pointers... just
>> off the top of my head.
> 
> Actually I don't see why you can't use a delegate for this. The only 
> difference is that it won't be virtual.

Type-safety. I mean, you can do this if you want:

	auto funcptr = &Object.toString;
	auto object = new Object;

	// now call our function using object
	string delegate() deleg;
	deleg.ptr = cast(void*)object;
	deleg.funcptr = funcptr;

but this is not type-safe: the funcptr type ("string function()") is 
actually wrong (it'll only work if called from a delegate) and the 
object pointer the in the delegate is a void*. All Manu is asking is 
that funcptr is of a correct type so you can call it directly by 
supplying "this" as an argument, like this:

	funcptr(object);

The problem is that this "correct type" for the function pointer does 
not exist currently. Calling a member function uses a different ABI, so 
the type needs to know somehow its a pointer to a member function (and 
that its first parameter is "this"), otherwise the generated code at 
the call site will be all wrong.

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca/



More information about the Digitalmars-d mailing list