Templates and Associative Arrays

Simen Kjaeraas simen.kjaras at gmail.com
Sun Jan 20 22:29:04 PST 2008


dsimcha <dsimcha at yahoo.com> wrote:

> Is it possible to create a template function that treats regular dynamic
> arrays the same as associative arrays?  For example, I want to create a  
> very
> simple template function to extract a column from a 2-d array of T's.   
> If the
> array is non-associative in both dimensions, the function could be  
> trivially
> implemented as:
>
> T[] extract_column(T)(T[][] data, size_t column_to_extract)
> {
>     T[] extracted_column;
>     foreach(row; data)
>     {
>         extracted_column~=row[column_to_extract];
>     }
>     return extracted_column;
> }
>
> However, in the case of an associatve array, I cannot think of any  
> obvious way
> to make this work without essentially implementing it four different  
> times,
> once each for an associative and non-associative row dimension and  
> likewise
> for the column dimension.

If you're asking whether there is some uniform way to declare an  
associative and a normal dynamic array, then I fear you're out of luck.  
Perhaps this should be possible by some strange magic like int[void] foo;  
to declare a normal array...
I did make a template that works though, but it's an ugly way to do this:


template foo(T, U, V)
{
	mixin("T[] extract_column(T[" ~ ((U.stringof == "void")?"":U.stringof) ~  
"][" ~ ((V.stringof == "void")?"":V.stringof) ~ "] data, size_t  
column_to_extract)
	{
	    T[] extracted_column;
	    foreach(row; data)
	    {
	        extracted_column~=row[column_to_extract];
	    }
	    return extracted_column;
	}");
}

alias foo!(int, void, void) bar;

int main()
{
	int[][] baz;
	baz.length = 1;
	baz[0].length = 1;
	baz[0][0] = 4;
	auto foobar = bar.extract_column(baz, 0);
	writefln(foobar);
	
	return 0;
}


prints [4]

This might be possible to do in a better way, of course.

Simen Kjaeraas



More information about the Digitalmars-d mailing list