user2076774
user2076774

Reputation: 405

"No matching function call to..." for template function

I am trying to do a binary search template, when I run it using the primitive "int" the code runs fine but when I run it with "string" I get the error

"No matching function call to binary_search_template"

Why does it work with ints but not strings?

Here is the code

main{
 std::vector<string> e;
    e.push_back("a");
    e.push_back("b");
    e.push_back("c");

int index = binary_search_template(e, 0, d.size()-1.0, "a"); //error for strings but not ints

}

header file

template<typename T>
int binary_search_template(std::vector<T>& a, int from, int to, T value);

template<typename T>
int binary_search_template(std::vector<T>& a, int from, int to, T value)
{
    if (from > to) {
        return -1;
    }
    int mid = (to + from)/2;

    if (a[mid] == value ) {
        return mid;
    }else if (a[mid] < value) {
        return binary_search_template(a, mid+1, to, value);
    }else {
        return binary_search_template(a, from, mid, value);
    }
}

Upvotes: 0

Views: 609

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154035

The compiler sees two candidates for the type T when you use a std::vector<std::string> and a string literal:

  1. std::string
  2. char const*

You'll need to make up you mind, e.g., by passing the argument as std::string("a"). Alternatively you could use an additional template parameter for the last argument.

Upvotes: 3

Related Questions