C++ で __gnu_cxx::hash_map と boost::hash をナチュラルに使う

tr1 で unordered_set が追加されて、バンザーイという方も多いはず。とはいっても、未だに gcc 3.4 な環境は多いわけでして、例えば cygwin とか。そういう環境では、しょうがないので __gnu_cxx::hash_map に逃げるわけですが、これが string に対して hash 関数を定義してなかったりで、ちょっとメンドクサイ。そこで、boost::hash の登場なんですが、毎回 boost::hash と書くのが面倒なんですよね。そこで、ちょっとアレな解決策を・・・。

#include <ext/hash_map>
#include <boost/functional/hash.hpp>

#include <iostream>
#include <string>

template <typename K, typename V>
class hashmap : public __gnu_cxx::hash_map<K, V, boost::hash<K> > {
};

int main() {
  hashmap<std::string, int> h;
  h["hoge"] = 1;
  std::cout << h["hoge"] << std::endl;
}

template の typedef はできないようなので、ええい public 継承してしまえという寸法。const_iterator とかもそのまま使えます。pair を key とする hashmap も自然に定義できます。