c++functionc++17overloadingambiguous

Ambiguous Error At Overloaded Functions in C++17


I wrote c++17 code below :

class Myclass{
public:
    Myclass()
    {
        std::cout << "ctor\n";
    }

    Myclass(const Myclass&)
    {
        std::cout << "copy ctor\n";
    }

    Myclass(Myclass&&)
    {
        std::cout << "move ctor\n";
    }

    int x;
};

void foo(Myclass mc)
{
    std::cout << "void foo(Myclass mc)\n";
}

void foo(Myclass&& mcrr)
{
    std::cout << "void foo(Myclass&& mcrr)\n";
}

int main()
{
    foo(Myclass{});
}

But, I was given "call of overloaded foo(Myclass) is ambiguous" error. What is problem? I expected that second function will be called.


Solution

  • void foo(Myclass mc) and void foo(Myclass&& mcrr) are equally good matches.

    Make the first function void foo(const MyClass& mc) and your call will match the second foo since it wont require any conversion.

    Demo