fenix
fenix

Reputation: 13

Specializing hash class for nested class C++

The goal is to specialize std::hash to work with a subclass called Node.

And the relevant class is:

template<typename T,
         typename Hash = std::hash<T>,
         typename Pred = std::equal_to <T>,
         typename Alloc = std::allocator<T>>
class disjoint_set
{
public:
    typedef Hash hasher;
    typedef Pred value_equal;
    typedef Alloc allocator_type;

protected:
    class Node;
    unordered_set<Node> table;
    // friend class std::hash; // possible solution

    class Node
    {
    public:
         T data;
         // .......
    };
};

I would like to have a hash function as follows:

size_t operator()(const Node& node) const { return hasher(node.data); }

However, the hasher specialization must be in namespace std. One solution I found was to make the specialization a friend class but in that case I'm unsure how to access the template arguments of the main class?

Upvotes: 1

Views: 152

Answers (1)

Barry
Barry

Reputation: 303750

You can't specialize on a nested class of a class template - you'd have to write something like:

template <class T>
struct hash<typename Outer<T>::Inner> { ... };

But that's a non-deduced context, so can never work.

Instead, just pull your Node out of disjoint_set and make it a standalone class template. At that point, specializing std::hash becomes straightforward and using it inside of disjoint_set is just as easy.

Upvotes: 1

Related Questions