pointers-to-members, (custom) array implementation
Jarrett Billingsley
kb3ctd2 at yahoo.com
Wed Feb 7 18:54:52 PST 2007
"Wolfgang Draxinger" <wdraxinger at darkstargames.de> wrote in message
news:uoaq94-f0c.ln1 at darkstargames.dnsalias.net...
> I'm currently in a discussion D vs. C++ and in some points I must
> admit, that the other side has some point, I must admit, too:
>
> Pointers to members are a feature that D currently lacks, but
> sometimes they are quite usefull and can't be replaced by
> delegates.
>
> E.g. say you got a class "foo" which has several member functions
> of the same prototype and several member variables. Now you want
> to write some function that performs some action on the class,
> but is not fixed on certain members. That function would accept
> the instance of a class, and pointers-to-members as parameters.
> The whole thing could be used in a foreach loop.
>
It's not quite as elegant as pointers-to-members, but it's something:
class A
{
static A members;
static this()
{
members = new A();
}
int fork()
{
return 1;
}
int knife()
{
return 2;
}
}
void func(A a, int delegate()[] members...)
{
foreach(member; members)
{
member.ptr = a;
writefln(member());
}
}
void main()
{
A a = new A();
func(a, &A.members.fork, &A.members.knife);
}
The ugly parts are (1) having to create an instance of A in order to get the
offsets of the member functions (the static 'members' variable) and (2)
having to set the delegate .ptr before calling it, rather than just calling
something like "a.*member()".
I think pointers-to-members have a bad reputation but I agree that they can
be really useful in some cases.
More information about the Digitalmars-d
mailing list