【问题标题】:Specializing hash class for nested class C++专门用于嵌套类 C++ 的哈希类
【发布时间】:2016-06-04 03:02:48
【问题描述】:

目标是专门化 std::hash 以使用名为 Node 的子类。

而相关的类是:

template<typename T,
         typename Hash = std::hash<T>,
         typename Pred = std::equal_to <T>,
         typename Alloc = std::allocator<T>>
class disjoint_set
{
public:
    typedef Hash hasher;
    typedef Pred value_equal;
    typedef Alloc allocator_type;

protected:
    class Node;
    unordered_set<Node> table;
    // friend class std::hash; // possible solution

    class Node
    {
    public:
         T data;
         // .......
    };
};

我想要一个哈希函数如下:

size_t operator()(const Node& node) const { return hasher(node.data); }

但是,哈希特化必须在命名空间std 中。我发现的一种解决方案是将专业化设为 朋友类,但在这种情况下,我不确定如何访问主类的模板参数?

【问题讨论】:

    标签: c++ templates hash namespaces specialization


    【解决方案1】:

    您不能专注于类模板的嵌套类 - 您必须编写如下内容:

    template <class T>
    struct hash<typename Outer<T>::Inner> { ... };
    

    但这是一个非推断的上下文,因此永远无法工作。

    相反,只需将您的Node 拉出disjoint_set 并使其成为独立的类模板。到那时,专门化std::hash 变得简单,在disjoint_set 内部使用它也同样简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多