Templates and Associative Arrays - boring version

Don Clugston dac at nospam.com.au
Tue Jan 22 05:20:45 PST 2008


downs wrote:
> dsimcha wrote:
>> Wow, that is an impressive hack.  While it's certainly better than nothing, this
>> is one area where it would be nice if the template system in D improved to make
>> this cleaner and more obvious.  I am trying to learn/use D to replace scripting
>> languages for programs involving huge CSV files, because the scripting languages
>> are painfully slow for this.  I have a small custom library in PHP (which I use
>> for general-purpose, not just web, scripting) for handling CSVs, and am trying to
>> port it to D, and creating simple, clean templates for processing arrays without
>> knowing at compile time whether they are regular or associative is a major hangup.
> 
> Alright, so here's the boring version :)
> 
>> import std.stdio;
>>
>> template Init(T) { T Init; }
>>
>> template ElemType(T) {
>>   static if (is(typeof(Init!(T).keys)))
>>     alias typeof(Init!(T)[Init!(T).keys[0]]) ElemType;
>>   else
>>     alias typeof(Init!(T)[0]) ElemType;
>> }
>>
>> void main() {
>>   writefln(ElemType!(ElemType!(int[][])).stringof);
>>   writefln(ElemType!(ElemType!(float[string][string])).stringof);
>>   writefln(ElemType!(ElemType!(real[float][])).stringof);
>> }
> 
>  --downs

Do you really need the Init template ? Why not just:

template ElemType(T) {
   static if (is(typeof(T.keys)))
     alias typeof(T[T.keys[0]]) ElemType;
   else
     alias typeof(T[0]) ElemType;
}



More information about the Digitalmars-d mailing list