Specializing std::hash<>

  • Follow


I want to provide a hashing functor for a class I am writing so that it
can be a key in an unordered associative container.

Let us call the class MyClass.  Is it acceptable to specialize
std::hash directly (requiring it to be specialised within the std
namespace as std::hash<MyClass>), in order that the default hash type
for unordered associative containers will work with MyClass without
further intervention, or is that regarded as unlawful so that I would
have to explicitly pass a named functor type existing outside std
namespace when instantiating any relevant associative container?

Chris


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Chris 3/25/2011 10:02:35 AM

On 2011-03-25 17:02, Chris Vine wrote:
> Let us call the class MyClass.  Is it acceptable to specialize
> std::hash directly (requiring it to be specialised within the std
> namespace as std::hash<MyClass>), in order that the default hash
> type for unordered associative containers will work with MyClass
> without further intervention, [...]

Specializing std::hash for MyClass is allowed in that case and common
practice. Citing from the C++0x N3000 draft, 17.6.3.2.1.1 (but the
standards should contain a similar section):

"[...] A program may add a template specialization for any standard
library template to namespace std only if the declaration depends on a
user-defined type of external linkage and the specialization meets the
standard library requirements for the original template and is not
explicitly prohibited."

Cheers

Thomas Luzat


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Thomas 3/26/2011 12:14:06 PM


1 Replies
491 Views

(page loaded in 0.092 seconds)

Similiar Articles:




7/24/2012 6:29:54 PM


Reply: