C++ 未为类引用定义哈希?

C++ 未为类引用定义哈希?,c++,c++11,unordered-map,C++,C++11,Unordered Map,我有一个有趣的错误,我在std::unordered_map中使用了一个自定义类作为键。我已经为这个自定义类实现了一个哈希函数 如果我创建一个std::unordered_map这样一切都可以正常运行: std::unordered_map <Component, int> myMap; 错误3 C338:C++标准不提供这种类型的哈希值。 你知道我该怎么做吗 class Component { public: GUID id; Component() {

我有一个有趣的错误,我在
std::unordered_map
中使用了一个自定义类作为键。我已经为这个自定义类实现了一个哈希函数

如果我创建一个
std::unordered_map
这样一切都可以正常运行:

std::unordered_map <Component, int> myMap;

错误3 C338:C++标准不提供这种类型的哈希值。 你知道我该怎么做吗

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
类组件
{
公众:
GUID id;
组件()
{ 
generateGUID(&id);
}
布尔运算符==(常量组件和其他)常量
{
返回compareGUID(id,other.id);
}
};
名称空间标准
{
模板
结构散列
{
std::size\u t运算符()(常量组件和cmp)常量
{
使用std::size\u t;
使用std::hash;
return hash()(cmp.id);//GUID哈希也已实现
}
};
}
std::无序映射cMap1;//编译ok
std::无序映射cMap2;//导致编译器错误

问题不在于如何正确覆盖
组件的哈希值&
。问题在于STL容器是用来存储对象的,而引用不是对象。请注意,术语对象包括原语和指针,因为它们需要存储,而引用则不需要

为了克服您的问题,您应该研究能够将引用包装到对象中的代码,然后代码将成为:

#包括
#包括
#包括
使用名称空间std;
结构组件
{
尺寸标识;
};
名称空间标准
{
模板
结构散列
{
大小\u t运算符()(常量引用\u包装器和cmp)常量
{
返回cmp.get().id;
}
};
}
无序映射;
如果您不想使用引用包装器,那么应该使用指针(
Component*
)作为键

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
#include <iostream>
#include <unordered_map>
#include <functional>

using namespace std;

struct Component
{
    size_t id;
};

namespace std
{
    template<>
    struct hash<reference_wrapper<Component>>
    {
        size_t operator()(const reference_wrapper<Component>& cmp) const
        {
            return cmp.get().id;
        }
    };
}

unordered_map<reference_wrapper<Component>, int> mapping;