且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何制作std :: weak_ptr的C ++ 11 std :: unordered_set

更新时间:2023-11-13 14:32:40

由于unordered_sets基于哈希,因此您必须提供哈希

Since unordered_sets are hash-based you have to provide a hash function object for the std::weak_ptr data-type.

如果您查看unordered_set模板参数

If you take a look at the unordered_set template-parameters

template<class Key,
    class Hash = std::hash<Key>,
    class Pred = std::equal_to<Key>,
    class Alloc = std::allocator<Key> >
    class unordered_set;

您会注意到std :: unordered_set为您提供了默认的std :: hash<>模板参数.但是由于std :: hash确实仅提供特定集的专业化功能数据类型,您可能必须提供自己的数据.

you'll notice that std::unordered_set provides you with a default std::hash<> template parameter. But since std::hash does only provide specializations for a specific set of data types, you might have to provide your own.

您引用的错误消息告诉您,不存在std :: weak_ptr<>的std :: hash<>专业化,因此您必须为此提供自己的哈希函数:

The error-message you quoted tells you, that no std::hash<> specialization for std::weak_ptr<> exists, so you have to provide your own hashing function for that:

template<typename T>
struct MyWeakPtrHash : public std::unary_function<std::weak_ptr<T>, size_t> {
   size_t operator()(const std::weak_ptr<T>& wp)
   {
      // Example hash. Beware: As zneak remarked in the comments* to this post,
      // it is very possible that this may lead to undefined behaviour
      // since the hash of a key is assumed to be constant, but will change
      // when the weak_ptr expires
      auto sp = wp.lock();
      return std::hash<decltype(sp)>()(sp);
   }
};

修改: 您还需要提供一个相等函数,因为没有为weak_ptr提供std :: equal_to. 通过在***上的平等比较std :: weak_ptr" ,采取一种可能的方式进行操作:

You also need to provide an equality function, since no std::equal_to for weak_ptr is provided. Taking a possible way to do this from "Equality-compare std::weak_ptr" on ***:

template<typename T>
struct MyWeakPtrEqual : public std::unary_function<std::weak_ptr<T>, bool> {

   bool operator()(const std::weak_ptr<T>& left, const std::weak_ptr<T>& right)
   {
      return !left.owner_before(right) && !right.owner_before(left);
   }
};

所有这些结合在一起,我们得到了以下东西:

All combined this gives us the following:

std::unordered_set<std::weak_ptr<T>,
                   MyWeakPtrHash<T>,
                   MyWeakPtrEqual<T>> wpSet;