Search code examples
c++c++11move-semanticsoverload-resolution

Ambiguity in calling function. Implicit conversion?


#include <string>

void f(std::string&& rref){
}

void f(std::string s){ 
}

int main() {
    std::string s = "s";
    f(std::move(s));
}

This code causes an ambiguity and I don't know why, perhaps, I made explicit conversion to rvalue reference.

My idea is that rvalue reference can be implicitly converted to just lvalue. But I am not sure. Please explain.


Solution

  • std::string can be initialized from an rvalue of type std::string . So the second function is a candidate.

    It's not a feasible idea to have value and rvalue-reference overloads. A more normal setup is to have rvalue-reference, and lvalue-reference overloads:

    void f(std::string&& rref);
    void f(std::string & lref);   // or const&
    

    This would cover all the use cases.