dimanche 27 décembre 2015

Hash Not Defined for Class Reference?

I have a funny error occuring where I have a custom class I am using as keys in a std::unordered_map. I have implemented a hash function for this custom class.

If I create an std::unordered_map like so everything runs fine:

std::unordered_map <Component, int> myMap;

But if I create a std::unordered_map where the keys are references it complains there is no implemented hash function for this type:

std::unordered_map <Component&, int> myMap; 

Error 3 error C2338: The C++ Standard doesn't provide a hash for this type.

Any idea how I can get this to work?

class Component
{
public:
    GUID id;

    Component()
    { 
        generateGUID(&id);
    }

    bool operator== (const Component& other) const
    {
        return compareGUID(id, other.id);
    }
};

namespace std
{
    template<>
    struct hash<Component>
    {
        std::size_t operator()(const Component& cmp) const
        {
            using std::size_t;
            using std::hash;

            return hash<GUID>()(cmp.id); // GUID hash has also been implemented
        }
    };
}


std::unordered_map<Component, int> cMap1;  // compiles ok
std::unordered_map<Component&, int> cMap2;  // causes compiler error

Aucun commentaire:

Enregistrer un commentaire