Search code examples
d

Type-inferring a delegate argument with unknow number of known-typed arguments


If you define a function that accepts a delegate, D can type-infer the delegate arguments when you call that function. So if I write a function with the signature:

void foo(void delegate(int,string) dlg)

I can call it using:

foo((a,b){});

and D will infer that a is int and b is string.

But what if I don't know in advance how many arguments the delegate will have? if I write

void foo(T...)(void delegate(T) dlg)

I can call:

foo((int a,string b,char c,boolean d){});

But I had to specify the types for each argument.

Now, I want foo to accept a delegate with any number of arguments - all of the same type. So I can call:

foo((a,b,c,d,e,f,g){});

and D will infer that a to g are all strings.

Note that what I need is not a varidaic function. dlg itself does not accept any number of arguments, it is foo that accepts a delegate with any number of arguments.

Is it possible to do this in D?

EDIT:
Actually, it would be better if I can define a default argument, so I can write

foo((a,b,int c,d){});

and a,b and d will be strings while c will be int.


Solution

  • It could be an enhancement request. But for now you can pass it at compile-time as an alias:

    import std.stdio;
    
    void foo(alias dlg)()
    {
        dlg(1, 2.0, [3], "a");
        dlg(1.0, 2, [[3]], "b");
    }
    
    void main()
    {
        foo!((a, b, c, d) { writefln("%s %s %s %s", a, b, c, d); } )();
    }