这是目标(当然是简化了代码):
#include <set>
struct Node
{
int Value;
std::set<Node*, CompareNodes> Children;
};
struct CompareNodes
{
bool operator()(const Node* l, const Node* r)
{
return l->Value < r->Value;
}
};
但这不能编译; CompareNodes
类型在 Node
内部遇到时是未知的。我可以颠倒顺序,但我遇到了相反的问题——Node
在 CompareNodes
中遇到时是未知的。在这两种情况下,前向声明都无济于事,因为每种类型都以需要其完整定义的方式使用另一种类型。一个丑陋的解决方法是:
#include <set>
template<typename T>
struct CompareNodes
{
bool operator()(const T* l, const T* r)
{
return l->Value < r->Value;
}
};
struct Node
{
int Value;
std::set<Node*, CompareNodes<Node>> Children;
};
有没有更好的方法?如果即使 Node
是内部类,答案仍然有效,则加分。
最佳答案
您可以使用嵌套类作为比较器:
#include <set>
struct Node
{
struct CompareNodes
{
bool operator()(const Node& l, const Node& r)
{
return l.Value < r.Value;
}
};
int Value;
std::set<Node, CompareNodes> Children;
};
关于c++ - 包含一组自身和自定义比较器的类——循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40750630/