0
#include <vector>
#include <iostream>

using namespace std;

static const int NOT_FOUND = -1;

template <class sequence, class T>
int binarySearch(sequence& seq, int low, int high, T& item)
{
    //..
}

template <class sequence, class T>
int binarySearch(const sequence& seq, const T& item)
{
    if (seq.size() == 0)
        return NOT_FOUND;
    return binarySearch(seq, 0, seq.size() - 1, item);
}

int main()
{
    vector<int> t1 = {0, 3 ,45, 94};
    cout << binarySearch(t1, 0);
    //binarySearch(t1, 0, t1.size() - 1, 45);
    return 0;
}

Why does the compiler not accept:

template <class sequence, class T>
int binarySearch(sequence& seq, T& item)

?

Furthermore, why does the program as stated compile, but calling

binarySearch(t1, 0, t1.size() - 1, 45);

from main not compile?

The compiler error in any case is "No matching function for call to 'binarySearch'.

Steve M
  • 9,296
  • 11
  • 49
  • 98
  • One issue that never use `t1.size()` with an int, `size()` returns an unsigned value, so you can first convert it to int, and then use it, like `int(t1.size())-1` – theharshest Jan 18 '15 at 04:01

1 Answers1

2

The problem is you cannot bind a temporary object to a non-const reference.

binarySearch(t1, 0);
                 ^---- this is a temporary

If you stored 0 in a variable and used that, the non-const version would work.

§ 8.5.4

— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is copy-list-initialized or direct-list-initialized, depending on the kind of initialization for the reference, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. —end note

Borgleader
  • 15,826
  • 5
  • 46
  • 62