Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call of overloaded function is ambiguous although different namespace

Tags:

c++

ambiguous

I do understand why the following would be a problem if no namespaces were used. The call would be ambiguous indeed. I thought "using stD::swap;" would define which method to use.

Why does it work for "int" but not a "class"?

    #include <memory>

    namespace TEST {

    class Dummy{};

    void swap(Dummy a){};
    void sw(int x){};

    }

    namespace stD {

    void swap(TEST::Dummy a){};
    void sw(int x){};

    class aClass{
    public:
        void F()
        {
            using stD::swap;
            TEST::Dummy x;
            swap(x);
        }

        void I()
        {
            using stD::sw;
            int b = 0;
            sw(b);
        }
    };

    }

This is the error message:

    ../src/Test.h: In member function ‘void stD::aClass::F()’:
    ../src/Test.h:26:9: error: call of overloaded ‘swap(TEST::Dummy&)’ is ambiguous
       swap(x);
             ^
    ../src/Test.h:26:9: note: candidates are:
    ../src/Test.h:17:6: note: void stD::swap(TEST::Dummy)
     void swap(TEST::Dummy a){};
          ^
    ../src/Test.h:10:6: note: void TEST::swap(TEST::Dummy)
     void swap(Dummy a){};
          ^

I thank you very much in advance for an answer.

like image 320
Lycosa Avatar asked Mar 08 '23 20:03

Lycosa


1 Answers

This line is using argument dependent lookup

TEST::Dummy x;
swap(x);

So it will find both void stD::swap(TEST::Dummy) as well as void TEST::swap(TEST::Dummy) because x carries the TEST:: namespace.

In the latter case int b = 0; the variable b is not in a namespace, so the only valid function to call would be stD::sw due to your using statement.

like image 153
Cory Kramer Avatar answered Apr 30 '23 11:04

Cory Kramer