我正在尝试做以下事情:
boost::unordered_map<boost::flyweight<std::string>, boost::flyweight<std::string> > map;
boost::flyweight<std::string> foo(name);
map[foo] = foo;
但是编译器报错:“error C2665: 'boost::hash_value' : none of the 17 overloads could convert all the argument types”。
但是我已经定义了下面的函数:
std::size_t hash_value(const boost::flyweight<std::string> & b)
{
boost::hash<std::string> hasher;
const std::string & str = b.get();
return hasher(str);
}
bool operator==(const boost::flyweight<std::string>& f, const boost::flyweight<std::string> & second)
{
return f.get() == second.get();
}
但是它无法编译。
我需要做什么来让boost unordered_map支持flyweight?
[编辑] 我使用以下代码使其工作:
struct flyweight_hash
{
std::size_t operator()(const boost::flyweight<std::string> &elm) const
{
boost::hash<std::string> hasher;
const std::string & str = elm.get();
return hasher(str);
}
};
将其作为模板参数传递给map的构造函数:
boost::unordered_map<boost::flyweight<std::string>, boost::flyweight<std::string> , flyweight_hash > map;
在这种情况下,我不明白为什么重载 hash_value 没有起作用。
boost::unordered_map
的默认哈希函数似乎没有通过using boost::hash_value; return hash_value(key);
触发 ADL,所以它才不好。不过我现在无法检查。 - Xeoboost::hash
,而不应该特定于unordered_map
。至少文档是这样说的。 - pmr