title: Specializing std::hash for nested class in a template class
body: <p>I have a template class <code>Baz</code> which contains a nested class <code>Sub</code>. I'd like to define a hash function for this subclass by specializing std::hash. However, it doesn't seem to work.</p>
  
  <pre><code>#include &lt;functional&gt;
  
  struct Foo {
      struct Sub {
      };
  };
  
  template &lt;class T&gt;
  struct Bar {
  };
  
  template &lt;class T&gt;
  struct Baz {
      struct Sub {
          int x;
      };
  };
  
  // declare hash for Foo::Sub - all right
  namespace std {
      template &lt;&gt;
      struct hash&lt; Foo::Sub &gt;;
  }
  
  // declare hash for Bar&lt;T&gt; - all right
  namespace std {
      template &lt;class T&gt;
      struct hash&lt; Bar&lt;T&gt; &gt;;
  }
  
  // declare hash function for Baz&lt;T&gt;::Sub - doesn't work!
  namespace std {
      template &lt;class T&gt;
      struct hash&lt; Baz&lt;T&gt;::Sub &gt;;
  }
  
  // Adding typename produces a different error.
  namespace std {
      template &lt;class T&gt;
      struct hash&lt; typename Baz&lt;T&gt;::Sub &gt;;
  }
  </code></pre>
  
  <p>Gcc 4.5.3 complains:</p>
  
  <pre><code>$ g++ -std=c++0x -c hash.cpp
  hash.cpp:34:30: error: type/value mismatch at argument 1 in template parameter list for ‘template&lt;class _Tp&gt; struct std::hash’
  hash.cpp:34:30: error:   expected a type, got ‘Baz&lt;T&gt;::Sub’
  hash.cpp:40:12: error: template parameters not used in partial specialization:
  hash.cpp:40:12: error:         ‘T’
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>What I'm really trying to do is implement a container which supports stable <em>references</em> (not in the C++ sense) to elements within it. I want to allow the user to insert these references into <code>std::unordered_set</code> and similar, and use them to access or modify existing elements efficiently. The following is just a mockup, not the exact container I'm implementing. The problem is in defining a hash function for the reference type.</p>
  
  <pre><code>template &lt;class T&gt;
  class Container {
  public:
      class Reference {
      public:
          // operator==, operator!=, operator&lt; ...., isNull()
      private:
          size_t index; // index into m_entries (or could be anything else)
          // possibly more stuff
      };
  
      Reference insert (const T &amp;value);
      Reference find (const T &amp;value);
      void remove (Reference r);
      Reference first ();
      Reference next (Reference prev);
  
  private:
      struct Entry { T value, ... };
  
      std::vector&lt;Entry&gt; m_entries;
  };
  </code></pre>