首先是代码
“文件.h”
namespace doge
{
struct A
{
void func() = 0;
};
struct Aa : public A
{
std::string id;
void func() override {}
};
template<T>
struct Aaa: public Aa
{
T data;
void func() override {}
};
class D
{
private:
std::unordered_map<Aa,int> intMap;
std::unordered_map<Aa,std::string> stringMap;
};
}
namespace std
{
template<> struct hash<doge::Aa>
{
std::size_t operator()(const doge::Aa & key)
{
return hash<string>()(key.id);
}
};
}
我在标题中收到错误,这似乎表明已生成多个散列代码。我在我的错误消息中得到了其中的 2 个,每个 unordered_map 一个,有人可以帮我找出问题所在。谢谢。
explicit specialization; 'std::hash<_Kty>' has already been instantiated
最佳答案
将散列的特化放在无序映射之前。
当您第一次使用无序映射(您的类型)时,散列已经实例化。事后对其进行专门化是错误的——这既是为了避免常见错误,也是为了让编译器的工作更轻松。您可以安全地“破坏”命名空间定义以专门化,然后继续添加到 doge 命名空间。
关于c++ - 明确的特化; 'std::hash<_Kty>' 已经实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619183/