November 22, 2004
Makeshift array literals

I think I once mentioned a while back (before D had its own vararg system) something to the effect that by adding array literals, we would achieve some of the power of variadic functions.  At least as far as a variable-length list of one type goes.

But now that we have variadic functions, we can use them to achieve some of the power of array literals!

This code does it.  And you can even use something that isn't a compile-time constant in one of these 'literals'.  Of course, there are limitations:

- every element must be exactly of the target type - no implicit conversions will work
- it's no use where you need a compile-time constant - but then again, does the static initialiser syntax work in all these cases?
- it doesn't enable you to nest a struct/union static initialiser in it, so you'll need your pseudo-constructors if you want to do this
- for some strange reason, it doesn't seem to be the slightest bit typesafe on classes.  I haven't tried structs and unions, but imagine these to be even worse at the moment....

Stewart.

----------
import std.stdarg;
import std.stdio;

template Array(T) {
    T[] Array(...)
    in {
        foreach (TypeInfo arg; _arguments) {
            assert (arg == typeid(T));
        }
    }
    body {
        T[] result = new T[_arguments.length];

        foreach (inout T element; result) {
            element = va_arg!(T)(_argptr);
        }

        return result;
    }
}

void main() {
    int[] data = Array!(int)(25, 300, 42, 8132941);

    print(data);
    print(Array!(int)(40, 98324, 192, 240, 8765, data[2]));

    foreach (long i; Array!(long)(429L, 20942L, 91923210893017, 400L)) {
        writef("%d ", i);
    }
    writefln();
}

void print(int[] data) {
    foreach (int i; data) {
        writef("%d ", i);
    }
    writefln();
}
November 28, 2004
Stewart,

    Thank you for this.  I think this is a great way for the
language features to handle a common need with a very
simple, direct syntax.

Regards,
Garett