template<class Key, class Value>
AVLTree<Key,Value>::AVLTree(){
this->lessThan = Key::operator<;
}
此代码应该使std::function<bool(Key, Key)> lessThan
字段等于键的&lt;默认情况下运算符但是,当我使用AVLTree<int,int>
尝试此操作时,我得到:
error: ‘operator<’ is not a member of ‘int’
我是否将此错误格式化,或者这在C ++中是不可能的?
答案 0 :(得分:8)
C ++中没有预先存在的函数可以在int
上执行比较。此外,即使Key
是类类型,您也无法知道它是成员还是非成员operator<
。
以下是一些替代方案:
使用std::less
,
this->lessThan = std::less<Key>();
使用lambda:
this->lessThan = [](const Key& k1, const Key& k2){ return k1 < k2; };
如果您将AVLTree
设计为标准库容器,则比较对象的类型应为类型模板参数Comp
默认为std::less<Key>
,并传入实例构造函数,默认为Comp()
。
答案 1 :(得分:4)
template<class Key, class Value>
AVLTree<Key,Value>::AVLTree()
{
this->lessThan = std::less<Key>();
}
答案 2 :(得分:1)
您需要为int
,double
,char
等内置类型实现模板专精化。无法在内置类型上查询关系运算符,导致你的代码失败。