Abhijit Abhijit - 1 month ago 17
C++ Question

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

Consider the following program

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);

I am using std::upper_bound to binary search a vector but fails while compiling

c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm(2609): error C2672: 'operator __surrogate_func': no matching overloaded function found

Considering the fact that
for implicit comparison without using a predicate, I cannot find a justified reason for the compiler to complain. Moreover, the error message is not quite meaningful as I do not see a reason for using a surrogate function here. Even if it is a case of using a functor
, it should not be an issue as
is less comparable with an integer. It's worth noting that
has an acceptable syntax.

Refer: http://rextester.com/WKK72283


As the specifications of std::upper_bound clearly states, it applies the comparison with the argument value on the left-hand side and the sequence element on the right-hand side. I.e. in your case that would be int < slot comparison. Your operator < does not support comparisons arranged in that specific order.

For std::upper_bound you'll need

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

which cannot be implemented as a member function.

Meanwhile, std::lower_bound applies the comparisons with the argument value on the right-hand side, i.e. slot < int comparisons.

Your original implementation will work for std::lower_bound, but not for std::upper_bound.