Thursday, November 3, 2011

Recursive Templates -- poly dimensional associative arrays

Another step to the poly dimensional iterators are the generic ploy dimensional arrays. These come in handy. The Trick to realize is that the types need to be predefined first so 2 typedefs are needed.

//built with mimggw g++ (gcc version 4.5.0 (GCC))
#include <iostream>
#include <map>
#include <string>
//ploy dimensional associative arrays 

template <int n, typename Key, typename Value > 
struct MultiDimMap
{
//problem here for types u cant reach inside of the yet to be defined struct and get its type. You need to have it predefinable.  
  typedef MultiDimMap<n-1, Key, Value>  InnerMapClass;
  typedef std::map<Key, InnerMapClass>  MapClass;
  
  InnerMapClass& operator[](Key key) { return map[key]; }

private:
  MapClass map;  
}; 

template <typename Key, typename Value > 
struct MultiDimMap<1, Key, Value > 
{
  typedef std::map<Key, Value> MapClass;

  Value& operator[](Key key) { return map[key]; }
private:
  MapClass map;  
}; 

int main()
{
  MultiDimMap<1, std::string, int> stringInt1DMap;
  
  stringInt1DMap["a"] = 2;
  
  MultiDimMap<2, std::string, int> stringInt2DMap;
  stringInt2DMap["a"]["b"] = 2;
  stringInt2DMap["a"]["c"] = 3;

  MultiDimMap<3, int, std::string> intString3DMap;
  intString3DMap[1][1][1] = "first";
  intString3DMap[1][1][2] = "second";
  intString3DMap[2][2][1] = "third";
  
  std::cout << intString3DMap[2][2][1] << std::endl;
  std::cout << stringInt2DMap["a"]["c"]  << std::endl;
}

No comments:

Post a Comment