Using custom C++ types in hash-containers
Using custom types in STL containers based on hashes (mostly the unordered ones) requires a custom hash function.
This can easily be done by adding a std::hash
template specialization for this custom type:
# include <unordered_set>
class CustomType {
public:
inline size_t calculate_hash() const noexcept {
return reinterpret_cast<size_t>(this);
}
};
template <>
struct std::hash<CustomType> {
std::size_t operator()(const CustomType& val) const {
return val.calculate_hash();
}
};
using CustomTypeSet = std::unordered_set<CustomType>;
Ensure defining the std::hash
in the std
namespace, otherwise the compiler may not find it.