10

我正在尝试执行以下操作:

boost::unordered_map<boost::flyweight<std::string>, boost::flyweight<std::string> > map;

        boost::flyweight<std::string> foo(name);
        map[foo] = foo;

但是编译器抱怨:“错误 C2665:'boost::hash_value':17 个重载中没有一个可以转换所有参数类型”。

但我已经定义了以下功能:

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 支持享元?

[编辑] 我让它使用以下代码:

    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);
        }
    };

并将其作为模板参数传递给地图的构造:

boost::unordered_map<boost::flyweight<std::string>, boost::flyweight<std::string> , flyweight_hash > map;

在这种情况下,我不明白重载 hash_value 的方式不起作用。

4

2 回答 2

7

boost::hashhash_value通过参数相关查找 (ADL)调用。您正在尝试为hash_valuenamespace 中的类定义一个函数boost。因此,您的hash_value函数也需要进入此命名空间才能使 ADL 正常工作。不幸的是,将函数添加到外部命名空间是相当邪恶的,应该避免。您使用自定义哈希的解决方案似乎很好。

一个小示例代码来说明:

namespace boost {
  // somewhere in boost
  template<typename T>
  std::size_t hash(const T& t) { 
    // call using ADL
    // e.g. if called with object of class type foo::bar this will
    // pick up foo::hash_value despite the lack of namespace
    // qualification
    return hash_value(t); 
  }
}

// your hash_value (presumably in the global namespace)
// not picked up by above call
std::size_t hash_value(boost::flyweight<T>...);

namespace boost {
  // this would be picked up but is slightly evil
  std::size_t hash_value(boost::flyweight<T>...);
}
于 2012-01-01T21:30:17.660 回答
6

对已经散列的东西进行散列是很可惜的。Flyweight 保留一个相等对象的单个实例,因此哈希这个实例的地址而不是它的内容更有效。我执行以下操作(在 中std,而不是在 中boost,因为我使用的是 C++11,所以我在扩展std::hash,而不是boost::hash):

namespace std
{
  template <typename T>
  struct hash<boost::flyweight<T, boost::flyweights::no_tracking>>
  {
    using value_type = boost::flyweight<T, boost::flyweights::no_tracking>;
    size_t operator()(const value_type& ss) const
    {
      hash<const void*> hasher;
      return hasher(&ss.get());
    }
  };
}

我已经确认这是设计使然,而不是偶然: http: //lists.boost.org/boost-users/2013/03/78007.php

于 2013-03-06T09:51:32.017 回答