To prepare a struct to be used in an unordered_set, a hashing function is required. This can either be accomplished by overloading operator size_t() (ew) or annoyingly making something like this:
namespace std
{
template<> struct hash<MyStruct> : public unary_function<MyStruct, size_t>
{
size_t operator()(const MyStruct& mystruct) const
{
return 0; //hash here
}
};
}
Is there any way to create an interface like so:
struct Hashable
{
virtual size_t hash() = 0;
};
And setup std::hash to work for any of its implementations? I’m pretty sure templates don’t work that way, so that’s left me in a bind. Is there a safe size_t idiom that could work sorta like the safe bool idiom for casting to size_t? Or something else? It’s silly writing out a new std::hash specialization for every single struct when a common interface and a member function in each struct would be far more convenient.
There is actually another solution:
Now, all you have to do is defining a free-function
hash_valuethat acceptsTorT const&as argument and returns asize_t.EDIT: changed
hashtohash_value, as it was in Boost.