从泛型命名空间向前声明类(在std::hash中)
Forward-declaring class from generic namespace (in std::hash
我正在努力向前声明。B引用A, A使用B的std::vector A和B都定义在泛型(无)命名空间中
在A的头文件中前向声明B对A中的成员是有效的。然而,我在同一个头文件中为A定义了哈希函数,这就造成了麻烦。
#include "B.h"
class B;
class A{
public:
std::vector<B> bs;
}
namespace std
{
template <>
struct hash<A>
{
size_t operator()(const A& k) const
{
std::size_t seed = 0;
boost::hash_combine(seed, k.foo);
boost::hash_combine(seed, k.bar);
for(B &b:k.bs){
boost::hash_combine(seed, b.abc);
}
return seed;
}
};
}
函数访问B的向量,因此也需要前向声明。然而,它不使用父头文件中的forward声明。不幸的是,我不能在名称空间std中再次前声明它,因为这会在定义之间造成歧义。任何想法?
您可以将hash<A>::operator()
的定义移动到源文件中。所以:
// A.h
#include <vector>
#include <functional>
struct B;
struct A {
std::vector<B> bs;
};
namespace std {
template <>
struct hash<A> {
size_t operator()(const A& ) const;
};
}
// A.cpp
#include "B.h"
// now, B is complete, so we can define operator()
size_t std::hash<A>::operator()(const A& k) const
{
std::size_t seed = 0;
boost::hash_combine(seed, k.foo);
boost::hash_combine(seed, k.bar);
for(const B& b : k.bs){
boost::hash_combine(seed, b.abc);
}
return seed;
}
相关文章:
- C++std::hash实现总是确定性的吗
- std::hash for std::chrono::duration
- 为什么不区分大小写适用于 std::unordered_set的 std::hash 函数?
- 错误:未使用不完整的类型'struct std::hash<>'无效
- 无法专门化 std::hash 以unordered_map存储自定义类型
- 为模板类嵌套类定义 std::hash 时出现编译错误
- Return value of std::hash ofr (x86/x64)
- STD :: HASH :: operator() - 例外保证
- STD :: HASH专业化仍然由STD :: Unordered_map未使用
- C++11:是否有理由为什么某些常规类型不应该专门使用“std::hash”
- 重新定义 std::hash 模板结构
- 为什么std::hash不专门用于std::reference_wrapper
- std::hash 是否保证在 stdlib 发行版中相同
- 专门针对类满足条件的“std::hash”
- 如何使用 std::hash 对缓冲区进行哈希处理
- 为类模板的枚举成员定义 std::hash
- 无法对指向成员使用 std::hash 的专用化
- c++11 std::hash函数对象类的线程安全性
- 我可以重写std::hash吗
- const和nonconst类型的部分std::hash专用化