easily convert any method/function to a delegate
Daniel Korsgaard
d__s__k at hotmail.com
Wed Jul 18 15:16:36 PDT 2007
BCS wrote:
> Daniel Korsgaard wrote:
>> two simple function templates that together will enable you to
>> mindlessly use delegates everywhere.
>>
>> Whee first post on this NG :D
>> .. hope you like it..
>>
>> -------------------
>>
> [...]
>
>> /// two functions that will convert any
>> R delegate(P) to_delegate(R, P...)(R delegate(P) dg)
>> {
>> // insanely advanced operation!
>> return dg;
>> }
>>
>> /// ditto
>> R delegate(P) to_delegate(R, P...)(R function(P) fp)
>> {
>> R delegate(P) dg;
>> dg.funcptr = fp;
>> dg.ptr = null;
>> return dg;
>> }
>
>
>
> IIRC that doesn't (quite) work because some functions pass an arg in the
> same place as methods pass "this"
Bummer :(
>
> However IIRC you /can/ pass the function pointer as the delegate ptr and
> then have the delegate code convert it back to the correct type and call
> it.
Aye ?!
>
> R delegate(P) to_delegate(R, P...)(R function(P) fp)
> {
> auto dg = delegate R(P p)
> {return (cast(R function(P))(cast(void*)this))(p);}
> dg.ptr = cast(void*)fp;
> return dg;
> }
Err.. where do you get that 'this' from?
Anyways, my idea was to cut of the additional call. But if it really
have to be there, this is a lot cleaner:
R delegate(P) to_delegate(R, P...)(R function(P) fp)
{
return delegate R(P p) { return fp(p); };
}
.. hope you like it..
More information about the Digitalmars-d
mailing list