如何将std ::函数分配给C 的操作员

How do I assign an std::function to an operator in C++?

本文关键字:操作员 分配 函数 std      更新时间:2023-10-16
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 ?

中是不可能的

在C 中没有预先存在的函数可以在int s上进行比较。此外,即使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()

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

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

您需要针对intdoublechar等内置类型实现模板专业化。失败。