member pointers
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Tue Mar 13 03:14:05 PDT 2007
Daniel Keep wrote:
> bc wrote:
>> am i being stupid or is there any chance of adding pointers to member
>> functions and pointers to data members to D? i can't see any way of
>> getting the same functionality through existing language constructs for
>> member functions... alias seems like it might at first but i can't get
>> it to work... and the offsetof syntax for data members seems buggy.
>> otherwise, congrats on designing a really cool language
>
[snip code]
>
> Delegates are your pointer to member functions. Pointers to data of an
> object are just as you would expect. Or did you have a different use in
> mind?
In C++, a "pointer to member" is a pointer to a _class_ member, not an
_instance_ member. That pointer can then be combined with an instance
and dereference to the member of that class. If the pointer is to a
virtual function, calling the function pointed to will call the correct
override for that instance. (the pointer type is a combination of type
of the class and the type of the member)
So there are basically three cases:
* pointer to data member: equivalent to typed offset into object
* virtual function: equivalent to typed offset into vtable
* non-virtual function: equivalent to function pointer (but still
requires "this" pointer)
As far as I know, D has no direct equivalent to this, though pointers to
data members could probably be trivially written as a template struct.
One complication with member function pointers is that the latter two
cases above must both fit into the same type (so a pointer to a member
function must be able to reference both virtual and non-virtual functions).
The compiler could probably easily implement this though. One way to
make this easier to implement would be to give non-virtual functions
vtable offsets as well, so the pointer can be just an offset into the
vtable instead of a struct or "tagged union" type of thing. That way
they can also remain the same size as a size_t.
Note: pointers to member functions can be up to 16 bytes in some popular
C++ compilers, though C++ does need to handle a few case that D doesn't
like multiple inheritance and classes that have only been
forward-declared, as well as classes that aren't allowed to contain a
vtable pointer)
More information about the Digitalmars-d
mailing list