I can't figure out how to do the following C++ code in D:

int arr[] = { 1, 3, 5, 7, 11 };

template <typename... T>
void foo(T... values) { }

template <typename... T>
void bar(T... values)
{
    foo((arr[values] * 10)...);
}

int main()
{
    bar(1, 3, 4); /* calls foo(arr[1] * 10,
                               arr[3] * 10,
                               arr[4] * 10); */
    return 0;
}


This is how I tried to do it in D, but it doesn't work:

import std.conv;
import std.typetuple;

int[5] arr = [ 1, 3, 5, 7, 11 ];

void foo(T...)(T values) { }

void bar(T...)(T values)
{
    foo(expandWrapped!("arr[@] * 10", values));
}

template expandWrapped(string fmt, X...)
{
    string compose()
    {
        string ret = "alias expandWrapped = TypeTuple!(";

        foreach (i; 0 .. X.length)
        {
            auto iStr = to!string(i);

            foreach (ch; fmt)
            {
                if (ch == '@')
                {
                    ret ~= "X[" ~ iStr ~ "]";
                }
                else
                {
                    ret ~= ch;
                }
            }

            if (i != X.length - 1)
            {
                ret ~= ",";
            }
        }
        ret ~= ");";
        return ret;
    }
    mixin(compose()); // [1]
}

void main()
{
    bar(1, 3, 4);
}

1) Error: variable arr cannot be read at compile time

Reply via email to