我有多个类重载std::hash运算符((。比方说:
A.h
class A
{
...
}
namespace std
{
template<typename T>
struct hash;
}
A.cpp
template<> struct std::hash<A>
{
public:
virtual std::size_t operator()(const A& joint) const noexcept
{
..
}
类似的类比如class B
和class C
现在class B
使用类似于的A的散列
boost::hash_combine(h, std::hash<A>{}(b.getA())
问题:error: use of deleted function std::hash<A>::hash()
我尝试过:A.h
namespace std
{
template<typename T>
struct hash;
}
B.h
class B
{
friend struct std::hash<A>;
}
您必须在A.h
中定义std::hash<A>
专门化,以便B
和C
能够看到该专门化的存在以及它有一个operator()
成员。
如果B
和C
不能"看到"std::hash<A>
专用化,那么它们将实例化主std::hash
模板,该模板被禁用,因为标准库不知道如何散列用户定义的类型A
。
如果在A.h
中声明了std::hash<A>
专用化,但没有定义它,那么B
和C
会将其视为一个不完整的类,这意味着不能调用operator()
。
所以必须在A.h
中定义std::hash<A>
。你可以这样做:
// A.h
namespace std {
template <> struct hash<A> {
std::size_t operator()(const A&) const noexcept { ... }
};
}
您也可以将operator()
的定义移动到A.cpp
文件:
// A.h
namespace std {
template <> struct hash<A> {
std::size_t operator()(const A&) const noexcept;
};
}
// A.cpp
namespace std {
std::size_t hash<A>::operator()(const A&) const noexcept { ... }
}