Function to convert functions to delegates

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Dec 23 18:15:46 PST 2006


I came up with this function to make it easier to make libraries that can 
take function pointers or delegates for things like callbacks.  Basically it 
creates a dummy struct to function as the context for the delegate, which 
then calls the original function.  I guess that's a thunk?  Anyway:

template DelegatizeImpl(alias fn)
{
    private import std.traits;

    static assert(is(typeof(fn) == function), "Delegatize - input is not a 
function");

    private alias ReturnType!(fn) RetType;
    private alias ParameterTypeTuple!(fn) ParamTypes;
    private alias RetType delegate(ParamTypes) DGType;

    private struct S
    {
        RetType func(ParamTypes params)
        {
            return fn(params);
        }
    }

    private S context;

    DGType Delegatize()
    {
        return &context.func;
    }
}

template Delegatize(alias fn)
{
    alias DelegatizeImpl!(fn).Delegatize Delegatize;
}

To use it, just make a function:

void func(int x, int y)
{
    writefln("func: ", x, ", ", y);
}

And then call it:

auto dg = Delegatize!(func)();
dg(4, 5); // prints "func: 4, 5"

The type of the delegate returned will have the same return type and 
parameter types as the source function.

One issue with this is that it doesn't support default parameters -- but 
then again, D doesn't support that when getting a delegate of an aggregate 
method period, so there's really no way around it. 





More information about the Digitalmars-d mailing list