【发布时间】:2014-07-12 02:32:51
【问题描述】:
我有一个自定义类二进制搜索树。我想将比较器类作为参数传递(默认为 std::less)。我搜索的大多数答案都使用 STL 对象,然后传递它们的自定义比较器。我想要一些不同的东西。
// 树类
template <class T,class Compare = less<T>>
class Tree
{
struct TreeNode
{
T data;
struct TreeNode * left;
struct TreeNode * right;
};
public:
void insert(T);
};
// 自定义比较器类
template <class T>
class CustomCompare
{
public:
bool compare(const T&, const T &);
};
template<class T>
bool CustomCompare<T>::compare(const T & a, const T &b)
{
cout << "calling custom comparator";
return a<b;
}
// 插入树中
template<class T,class Compare>
void Tree<T,Compare>::insert(T val)
{
// HOW DO I CALL COMPARE HERE? I tried this
if (compare(val->data , treeNode->data)) /// does not work.
// I get error - use of undeclared identifier compare.
//IF I DO THIS, I get error - expected unqualified id
Compare<T> x; // cannot create instance of Compare
// IF I DO THIS< I can create instance of Compare but cannot call function compare.
Compare x;
x.compare(....) -- Error no member named compare in std::less
}
我无法将 CustomCompare::compare 设为静态,因为我希望代码也适用于 std::less。
我希望问题很清楚。
注意:我知道我可以为将要使用它的类重载operator <。我正在为这些类的源代码不可用的情况做准备
【问题讨论】:
-
你必须创建一个
Compare的实例。 -
如果我这样做,我会收到错误:在 std::less 中没有名为 compare 的成员
标签: c++ stl comparator