Search code examples
c++overloadingambiguous-call

How to overload an in-place and a copying string manipulation functions?


I would like to be able to do the following:

std::cout << str_manip("string to manipulate");

as well as

std::string str;
str_manip(str);
std::cout << str;

For this, I have two functions

#include <string>

// copying
std::string str_manip(std::string str)
{
        // manipulate str
        return str;
}

// in-place
void str_manip(std::string& str)
{
        // manipulate str
}

but they produce the following error:

error: call of overloaded 'str_manip(std::__cxx11::string&)' is ambiguous

How can I overcome this?


Solution

  • The problem is with this call:

    std::string str;
    str_manip(str);
    std::cout << str;
    

    The compiler doesn't know which version of str_manip to call.

    You can change your functions to look like this:

    #include <string>
    
    // copying
    std::string str_manip(const std::string& str)
    {
            std::string dup = str;
            // manipulate dup
            return dup;
    }
    
    // in-place
    void str_manip(std::string& str)
    {
            // manipulate str
    }
    

    Now, the compiler knows that the ambiguous call has to be the function that takes the non-const parameter. You can also be sure that your call that returns a std::string to the << operator isn't modifying your string.