pointer to member without 'this' - mem_fun like

Jarrett Billingsley kb3ctd2 at yahoo.com
Tue Mar 18 06:29:45 PDT 2008


"Vlad" <b100dian at gmail.com> wrote in message 
news:47DFC12D.8020604 at gmail.com...
> Jarrett Billingsley wrote:
>> "Frits van Bommel" <fvbommel at REMwOVExCAPSs.nl> wrote in message 
>> news:fro9ip$dib$1 at digitalmars.com...
>>>> Thanks, this should do it - however I still need an(other) instance 
>>>> when passing the delegate, right?
>>> You *might* get away with using &Class.memberfn to fill in dg.funcptr. 
>>> But I've never tried this, so you might want to make sure it works 
>>> before using it for anything serious.
>>
>> It does work, at least in my experience.  Of course this bypasses any 
>> vtable lookup so you'll just be getting the implementation of the method 
>> from Class.
>
> It didn't work for me (see full code below)..

> (here's the code: change &author.name to &Author.name)

>     set_field!(Author,string)(author, &author.name);

No, that isn't going to work, because when you get &Author.name, you only 
have one half of the puzzle.  It's just a function.  You need to factor in 
the instance somehow.

void set_field(T,F)(T instance, void function(F) setter)
{
    void delegate(F) dg;
    dg.funcptr = setter;
    dg.ptr = cast(void*)instance;
    dg("zz");
}

This is one way to do it.  Another way is to have the code generated at 
compile time instead:

template set_field(char[] name)
{
    void set_field(T)(T instance)
    {
        mixin("instance." ~ name ~ " = `zz`;");
    }
}

...

set_field!("name")(author); 




More information about the Digitalmars-d-learn mailing list