Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

stdhash

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());
        }
    }; 
}
like image 538
Steve Lorimer Avatar asked Mar 31 '15 21:03

Steve Lorimer


1 Answers

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.

like image 158
Potatoswatter Avatar answered Sep 22 '22 19:09

Potatoswatter