错误 C2672:"运算符__surrogate_func":使用 std::upper_bound 时未找到匹配的重载函数
error C2672: 'operator __surrogate_func': no matching overloaded function found when using std::upper_bound
考虑以下程序
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) {}
};
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?