是否可以将指向unordered_set的指针<MyClass>作为 myClass 的一部分?

Is it possible to have pointer to unordered_set<MyClass> as a part of myClass?

本文关键字:gt MyClass 作为 myClass 一部分 lt unordered set 指针 是否      更新时间:2023-10-16

我的代码看起来像这样:

class Node : public bitset<BITS_COUNT> {
public:
    Node(string s) : bitset<BITS_COUNT>(s) {}
    void setGroup(unordered_set<Node>* newSet) { currentGroup = newSet; }
    unordered_set<Node>* getCurrentSet() { return currentGroup; }
private:
    unordered_set<Node>* currentGroup = nullptr;
};

但是编译器不允许我这样做,因为没有为类节点定义哈希函数。我希望它使用基类中的哈希函数,所以我这样做了:

namespace std
{
    template<>
    struct hash<Node>
    {
        size_t operator()(const Node& k) const
        {
            return k.hash();
        }
    };
}

但它仍然不起作用。如果我把它放在 Node delcaration 之前,k.hash() 是未定义的(我不能转发声明 Node:public bitset<>因为它是不可能的)。如果我把它放在类声明之后,我会收到错误,即类节点没有哈希函数。

如何解决这个问题?

谢谢弗兰克,你的评论对我来说实际上是一个解决方案。如果有人需要代码,它看起来像这样:

namespace std
{
    template<>
    struct hash<Node>
    {
        size_t operator()(const Node& k) const;
    };
}
class Node : public std::bitset<BITS_COUNT> {
public:
    Node(std::string s) : bitset<BITS_COUNT>(s) {}
    void setGroup(std::unordered_set<Node>* newSet) { currentGroup = newSet; }
    std::unordered_set<Node>* getCurrentSet() { return currentGroup; }
private:
    std::unordered_set<Node>* currentGroup = nullptr;
};
namespace std
{
    size_t hash<Node>::operator()(const Node& k) const
    {
        return k.hash();
    }
}