Confusing stuff with arrays

Jari-Matti Mäkelä jmjmak at utu.fi.invalid
Fri May 12 07:22:45 PDT 2006


Tom S wrote:
> Deewiant wrote:
>> Of course I managed to forget the most important question for me: is
>> there a
>> reasonable way of doing what I'm trying to do?
>>
>> I.e. is there a template or whatever which would allow me to properly
>> initialise
>> an array of type char[][2][] with, say, [["Foo", "bar"], ["Bar",
>> "foo"]] inline?

Yes, here's the Tom's array logic with some simple template magic (might
not be fully optimized, though):

import std.stdio;

template dynamicA(T){
  T[] dynamicA(T[] newArray...){
  	return newArray.dup;
  }
}

template staticA(T, int l) {
	T[l][] staticA(T[][] items...) {
		T[l][] tmp = new T[l][items.length];

		foreach(int i, T[] x; items) {
			assert (l == x.length);
			foreach(int j, T y; x) {
				tmp[j][i] = y.dup;
			}
		}

		return tmp;
	}
}

void main() {
    auto t = staticA!(char[], 2)(dynamicA!(char[])("Foo", "bar"),
dynamicA!(char[])("Bar", "foo"));

    foreach (a; t) {
        writef("[ ");
        foreach (x; a) {
            writef(x, ' ');
        }
        writefln(']');
    }
}

-- 
Jari-Matti



More information about the Digitalmars-d-learn mailing list