On 10.01.2012 14:43, Mike Parker wrote:
On 1/10/2012 10:05 PM, simendsjo wrote:
If I want to have a method taking a callback function, I have to specify
if it should take a function or delegate even if I don't really care.
What's the best way to accept either? I cannot see any wrapper for
something like this in std.typecons.

The simple way:

void callback(int i, void delegate(int) dg)
{
dg(i);
}

void callback(int i, void function(int) fn)
{
void wrap(int j)
{
function(j);
}
callback(i, &wrap);
}

I tried the following, but I get some error messages:

h(9, (int i) { writeln(i); });

t.d(46): Error: template t.h(F) if (isCompatibleFunction!(F,void function(int))) does not match any function template declaration t.d(46): Error: template t.h(F) if (isCompatibleFunction!(F,void function(int))) cannot deduce template function from argument types !()(int,void delegate(int))


template isCompatibleFunction(Src, Dest) {
    static assert(isSomeFunction!Src, "Source is not a function");
    static assert(isSomeFunction!Dest, "Destination is not a function");
    enum bool isCompatibleFunction =
        is(ParameterTypeTuple!Src == ParameterTypeTuple!Dest) &&
is(ParameterStorageClassTuple!Src == ParameterStorageClassTuple!Dest) &&
        is(ReturnType!Src == ReturnType!Dest);
}

void h(F)(int i, F callback) if(isCompatibleFunction!(F, void function(int))) {
    callback(i);
}

Reply via email to