www.digitalmars.com         C & C++   DMDScript  

D - compile-time arrays of types

I thought of a cool feature for D templates.

Allow us to manipulate arrays of types.  Arrays of types are compile-time
objects.  A way to have compile-time iteration over them would be essential.

What this is replacing is the C++ equivalent of boost::mpl::list.

The problem with boost::mpl::list is that it's really complicated.  Doing
any metaprogramming in C++ is a PITA because there are no native constructs
for it;  it's all just exploiting unintentional functionality of templates.
For that reason, writing compile-time if statements and looping constructs
is really hard.  You have to change all your logic into recursive functional
style, but even that is hard because C++ templates don't do lazy evaluation
(only evaluate template params that are used).

What I want is to be able to do this:

template int_ (int i)
{
    struct int_
    {
        const int value = i;
    }
}

struct int_list_
{
    type[] list = [instance int_(1).int_, instance int_(3).int_, instance
int_(4).int_];
}

template index_(type[] list, int idx)
{
    struct result
    {
        alias list[idx] type;
    }
}

int main()
{
    printf("%d\n", instance index_(int_list_.list, 0).result.type.value); //
prints 1
    printf("%d\n", instance index_(int_list_.list, 1).result.type.value); //
prints 3
    printf("%d\n", instance index_(int_list_.list, 2).result.type.value); //
prints 4
    return 0;
}

As you can see, the instance keyword really clutters things up.  Plus you
can't template anything directly;  it's all thru some wierd template scope
which surrounds the things you really want to deal with.  Clumsy, compared
to C++.

Another thing I'd like to be able to do is use compile-time lists to
generate struct or class members.  Algorithmically build structs.  One thing
that would help would be if and switch statements inside of structs.  These
aren't like the equivalents inside a code block;  they can only take
compile-time arguments and they do not introduce a new scope.

template makedata(type T, int count, bit constant, T[] initializer)
{
    struct datastruct
    {
        if (constant)
            const T[count] array = initializer;
        else
            T[count] array = initializer;
    }
}

int main()
{
    instance makedata(float, 4, true, float[7,9,3,4]).datastruct foo;
    printf("%f %f %f %f\n",foo.array[0], foo.array[1], foo.array[2].
foo.array[3]);
    return 0;
}

All this stuff is very hard or impossible to do in C++, and currently not
supported by D either.

Sean
Apr 27 2003