TR1以前のhash_mapをVisual Studio 2008とgccの両方で使う方法

趣味で書いているコードでハッシュを使った連想コンテナを使いたいのにTR1のunordered_mapが使えないという状況に遭遇した。仕方なくhash_mapで実装することにした。ところがVisual Studio 2008とgccで仕様が異なっており、コード互換性をとるために四苦八苦してしまった。以下が出来上がったコードである。

#ifdef _MSC_VER
#include <hash_map>
using stdext::hash_map;
#else
#include <ext/hash_map>
using __gnu_cxx::hash_map;
#endif

struct A {
	size_t hash;
	bool operator < (const A& rh) const {
		// (中略)
	}
	bool operator == (const A& rh) const {
		// (中略)
	}
	size_t GetHash() const {
		return hash;
	}
};

#ifdef _MSC_VER
namespace stdext {
	inline size_t hash_value(const A& rh) {
		return rh.GetHash();
	}
}
#else
namespace __gnu_cxx {
	template<> struct hash<A> {
		size_t operator()(const A& rh) const {
			return rh.GetHash();
		}
	};
}
#endif

hash_map<A, B> hoge;

名前空間を汚染しているあたりが御世辞にも良いコードとは言えない。バッドノウハウなので真似しないように。