0

Given a nested template class structure like the following:

template<class T> class A
{
  ...
public:
  ...
  class B;
};

I am wanting the std::hash function to work on the nested class so that it can be put in things like unsorted_map and unsorted_set, so I defined the nested class as:

template<class T> class A<T>::B 
{
  public:
    bool operator==(const A<T>::B &) const;
  ...
  friend struct std::hash<A<T>::B>;
};

And then tried adding a specialized std::hash structure for this type as follows:

namespace std
{
  template<class T> struct hash<A<T>::B>
  {
    bool operator()(const A<T>::B &x) const
    {
       ...
    }
  };
}

But the compiler complains vehemently when I try to define the custom std::hash function object like this.

The error message I get is unhelpful, as follows:

xyz.cc:17:38: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Tp> struct std::hash'
 template<class T> struct hash<A<T>::B>
                                      ^
xyz.cc:17:38: error:   expected a type, got 'A<T>::B'

I'm not sure how else I am supposed to express it, however.

Why is this wrong, and what must I do to to fix it?

Arun
  • 2,087
  • 2
  • 20
  • 33
markt1964
  • 2,638
  • 2
  • 22
  • 54

1 Answers1

1

You cannot.

Dependant types cannot be pattern matched against, as the general case requires inverting an arbitrary Turing-complete algorithm.

The easiest way is to make B an independant template, then typedef into A.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524