c++c++11stdhash

Why is std::hash not specialised for std::reference_wrapper?


I thought it would have been, but I can't find this in my standard library implementation (gcc-4.8.2).

Why is std::hash not already specialised for std::reference_wrapper?

#pragma once
#include <functional>

namespace std 
{
    template<typename T>
    struct hash<reference_wrapper<T>>
    {
        size_t operator()(const reference_wrapper<T>& r) const
        {
            return std::hash<T>()(r.get());
        }
    }; 
}

Solution

  • std::reference_wrapper is mostly used to provide reference semantics in utilities that default to copying values, such as std::bind.

    Direct use of std::reference_wrapper as in a container is essentially like a pointer (except that it is not nullable). Hashing of pointers (and smart pointers) follows reference (i.e. address) semantics.

    You can always provide your own hash function, of course. If you define it as a template over all pointers and smart pointers, then T* might be a better choice of value type rather than reference_wrapper<T>.

    Note, if you're already hashing objects and storing the hashes, you might eliminate duplicates by keeping everything in an unordered_map. Then value identity and object identity will be the same.