mercredi 4 août 2021

Why name lookup can't find std::swap when a base class has a swap function in C++? [closed]

I have a replica of what's inside my code

#include <utility>
using namespace std;

class Parent
{
    public:
        void swap(Parent*);
};
class A : public Parent 
{
    public:
        void handle();
};


void A::handle()
{

    long x = 1;
    long y = 2;
    swap(x,y);
}


int main()
{
    A v;
    v.handle();
    return 0;
}

The error log:

main.cpp: In member function 'void A::handle()':
main.cpp:21:10: error: no matching function for call to 'A::swap(long int&, long int&)'
  swap(x,y);
          ^
main.cpp:7:8: note: candidate: void Parent::swap(Parent*)
   void swap(Parent*);
        ^
main.cpp:7:8: note:   candidate expects 1 argument, 2 provided

To my understanding swap call inside A::handle() will trigger non-qualified lookup and because it will find swap name in the parent class that's a function, argument-dependent name lookup (ADL) will be called. Why the ADL here can't find the std::swap and use it ? Instead it tries to call the Parent's swap.

What I am missing here ?


Platform/Compiler: Red hat 6.7/ GNU 5.3.0

Platform/Compiler: Windows 10/ visual studio 2015

Aucun commentaire:

Enregistrer un commentaire