Call to member function is ambigous when overloading both vector of chars and string c++

Viewed 47

I want to overload a function the following way:

void f(string s){
    cout << "String case" << endl;
}

void f(vector<char> v){
    cout << "Vector case" << endl;
}

For the case I insert a string object or a vector object, everything is fine:

int main()
{
    string s = "hello";
    f(s); // Prints "String case"
    vector<char> v = {'a', 'b'};
    f(v); // Prints "Vector case"
    return 0;
}

But if I want to run f({'a', 'b'});, since the array can be automatically converted to both a string and a vector, I get error: call of overloaded ‘f()’ is ambiguous. Suppose I want to treat this case as a vector, how can I tell the compiler that?

2 Answers

Be explicit about which type the braces are being used to initialize:

f(string{'a', 'b'});
f(vector<char>{'a', 'b'});

If you provide a initializer_list<char> overload, calling f with a brace-initialized list such as {'a', 'b'} will select that overload as the best match.

You can just call the vector<char> overload explicitly from there.

void f(std::initializer_list<char> v) 
{
    f(std::vector<char>{v});  // call the vector version
}

and now the following call works as you want.

f({'a', 'b'}); // Prints "Vector case"

Here's a demo.

Note that you should be taking the string and vector<char> parameters by const& in the respective overloads.

Related