错误 C2672:"运算符__surrogate_func":使用 std::upper_bound 时未找到匹配的重载函数

error C2672: 'operator __surrogate_func': no matching overloaded function found when using std::upper_bound

本文关键字:重载 函数 upper surrogate 运算符 C2672 func 使用 错误 std bound      更新时间:2023-10-16

考虑以下程序

struct slot {
    int item;
    bool operator<(const int& right) const {
        return item < right;
    }
    slot(int item) : item(item) {}
};
int main() {
    std::vector<slot> rails;
    std::lower_bound(cbegin(rails), cend(rails), 5);
    std::upper_bound(cbegin(rails), cend(rails), 5);
}

我正在使用std::upper_bound二进制搜索向量,但在编译

时失败
c:program files (x86)microsoft visual studio 14.0vcincludealgorithm(2609): error C2672: 'operator __surrogate_func': no matching overloaded function found

考虑到std::upperbound使用operator<进行隐式比较而不使用谓词的事实,我找不到编译器抱怨的正当理由。此外,错误消息也不是很有意义,因为我没有看到在这里使用代理函数的理由。即使它是使用函子less<>的情况,它也不应该是一个问题,因为slot与整数的可比性较小。值得注意的是,std::lower_bound具有可接受的语法。

参考:http://rextester.com/WKK72283

正如std::upper_bound的规范明确指出的那样,它应用与左侧参数值和右侧序列元素的比较。也就是说,在你的情况下,这将是int < slot比较。您的operator <不支持按特定顺序排列的比较。

对于std::upper_bound,您需要

bool operator <(int left, const slot &s)
{
  return left < s.item;
}

不能作为成员函数实现。

同时,std::lower_bound应用与右侧实参值的比较,即slot < int比较。

您的原始实现将适用于std::lower_bound,但不适用于std::upper_bound

如上述答案所建议的,如果operator <可以实现为2个参数,则可以解决您的问题,但这将与成员函数实现相矛盾。但如果这变成了friend函数。结果表明,上述问题可以通过将其声明为友元函数来解决。

所以你的代码看起来就像这样:
struct slot {
    int item;
    friend bool operator<(int left, const slot &s)
    {
        return left < s.item;
    }
    friend bool operator<(const slot &s, int left)
    {
        return s.item < left;
    }
    slot(int item) : item(item) {}
};