Templates and Associative Arrays
    downs 
    default_357-line at yahoo.de
       
    Mon Jan 21 09:42:57 PST 2008
    
    
  
dsimcha 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.
Sure :)
Keep in mind, this code isn't tested .. but it should work in theory.
template Init(T) { T Init; }
import std.traits;
template NestedArrayElemType(T) {
  // this uses return-type autodeduction to basically say "if we iterated over the elements of T, and returned elem2; what would its type be?"
  alias ReturnType({ foreach (elem; Init!(T)) foreach (elem2; elem) return elem2; }) NestedArrayElemType;
}
alias NestedArrayElemType naet;
naet!(T) extract_column(T)(T data, size_t which) {
  naet!(T) res;
  foreach (row; data) res ~= row[which];
  return res;
}
 --downs
    
    
More information about the Digitalmars-d
mailing list