Sunday, September 09, 2007

hash_map band aid

Until TR1 is widely available, I'm using this wrapper to construct hash maps using the hash_maps distributed with Visual C++ and GCC. I thought it might be useful for someone else, so here goes.
#if defined(_MSC_VER)
#include <hash_map>
#elif defined(__GNUC__)
#include <ext/hash_map>
#endif

template <typename K> struct default_hash {};

template <> struct default_hash<int> {
 size_t operator()(int v) const
    { return size_t(v); }
};

template <> struct default_hash<unsigned int> {
 size_t operator()(unsigned int v) const
    { return size_t(v); }
};

#if defined(_MSC_VER)

template <
 typename KeyType,
 typename ValueType,
 class HashFun = default_hash<KeyType>
 >
struct HashMapOf
{
 struct Traits
 {
  static const size_t bucket_size = 4;
  static const size_t min_buckets = 8;

  HashFun hasher;

  inline size_t operator()
    (const KeyType& key) const
  {
   return hasher(key);
  }

  inline bool operator()
     (const KeyType& lhs,
      const KeyType& rhs) const
  {
   return lhs < rhs;
  }
 };


 typedef stdext::hash_map<
    KeyType,
    ValueType,
    Traits> Type;
};

#elif defined(__GNUC__)

template <
 typename KeyType,
 typename ValueType,
 class HashFun = default_hash<KeyType>
 >
struct HashMapOf
{
 typedef __gnu_cxx::hash_map<
    KeyType,
    ValueType,
    HashFun> Type;
};

#else
# error Unsupported toolchain.
#endif

No comments: