Search code examples
templatesmetaprogrammingdvariadic-templates

Mapping variadic template arguments in D


Is there any built-in, or library-provided way to map a set of variadic template arguments in D?

For example:

void foo(Args...)(Args args)
{
    bar(fun(args));
}

I want that to expand to:

void foo(Args...)(Args args)
{
    bar(fun(args[0]), fun(args[1]), fun(args[2]), /* ... */);
}

C++11 variadic templates support this. How do you do the same in D?


Solution

  • This is the best I've come up with:

    auto staticMappedCall(alias call, alias F, T...)(T t)
    {
        T a;
        foreach(i, arg; t)
                a[i] = F(arg);
        return call(a);
    }
    

    You use it like this:

        staticMappedCall!(bar,t)(1, 2);
    

    Where bar is the function to call and t is the transformation.

    void bar(int a, int b) { writeln(a, " ", b); }
    int t(int a) { return a*2; }
    
    staticMappedCall!(bar, t)(1, 2);
    
    > test
    2 4