简体   繁体   English

重载字符向量和字符串 c++ 时,调用成员 function 不明确

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

I want to overload a function the following way:我想通过以下方式重载 function:

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:对于我插入字符串 object 或向量 object 的情况,一切都很好:

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'});但是如果我想运行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 . ,由于数组可以自动转换为字符串和向量,我得到error: call of overloaded 'f()' is ambiguous Suppose I want to treat this case as a vector, how can I tell the compiler that?假设我想把这种情况当作一个向量,我怎么能告诉编译器呢?

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.如果您提供了一个initializer_list<char>重载,则使用大括号初始化列表(例如{'a', 'b'} )调用f将 select 将该重载作为最佳匹配。

You can just call the vector<char> overload explicitly from there.您可以从那里显式调用vector<char>重载。

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.请注意,您应该在各自的重载中通过const&获取stringvector<char>参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM