如何在C ++中为运算符指定std :: function?

时间:2016-06-22 20:38:58

标签: c++ templates c++11 operators function-object

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 ++中是不可能的?

3 个答案:

答案 0 :(得分:8)

C ++中没有预先存在的函数可以在int上执行比较。此外,即使Key是类类型,您也无法知道它是成员还是非成员operator<

以下是一些替代方案:

  1. 使用std::less

    this->lessThan = std::less<Key>();
    
  2. 使用lambda:

    this->lessThan = [](const Key& k1, const Key& k2){ return k1 < k2; };
    
  3. 如果您将AVLTree设计为标准库容器,则比较对象的类型应为类型模板参数Comp默认为std::less<Key>,并传入实例构造函数,默认为Comp()

答案 1 :(得分:4)

template<class Key, class Value>
AVLTree<Key,Value>::AVLTree()
{
    this->lessThan = std::less<Key>();
}

http://en.cppreference.com/w/cpp/utility/functional/less

答案 2 :(得分:1)

您需要为intdoublechar等内置类型实现模板专精化。无法在内置类型上查询关系运算符,导致你的代码失败。