0

I thought the point of using std::swap is if we swap some class,the swap will search the namespace the class is defined in,otherwise it use the std::swap.so I write some code to test it.

namespace np{
    class myclass{
        ...
    };
    void swap(const myclass&lhs,const myclass&rhs){
        cout<<"np::swap()"<<endl;
    }
}


int main()
{
   np::myclass m1,m2;
   using std::swap;
   swap(m1,m2);
}

but the result confused me.it use the std::swap directly,can someone explain why?thanks.

update

if function look for the better match,why the code below output "inside",it looks like using declaration hide the global foo,which is a better match

namespace np{
    class myclass{
        //...
    };
    void  foo(const myclass&m){
        cout<<"inside";
    }

}
void foo(np::myclass &m){
    cout<<"global";
}

int main()
{
   np::myclass m;
   using np::foo;
   foo(m);
} 
codesavesworld
  • 587
  • 3
  • 10

1 Answers1

3

In overload resolution your swap will loose against the std::swap one, because std::swap takes the arguments as non-const references, while your function takes them as const references, making it a worse match.

Just remove the const in the arguments and your ADL overload will be preferred.

In practical terms a swap function taking const arguments doesn't make much sense anyway.

walnut
  • 21,629
  • 4
  • 23
  • 59
  • thanks,I get it.if I remove namespace np,put the class and swap in global namespace,it still works,why using std::swap doesnt hide the swap outside – codesavesworld Dec 09 '19 at 02:43
  • please see the updated question – codesavesworld Dec 09 '19 at 03:37
  • @zenxy Ah ok, I was being imprecise in my last comment. `using np::foo;` does prevent the global `foo` from being found for the purpose of unqualified name lookup. It is also not found by ADL because it is not in the enclosing namespae of the class. A global `swap` is also prevented from being found for the purpose of unqualified name lookup when `using std::swap;` like this. A global `swap` is still found by ADL though when the class is also in the global namespace. – walnut Dec 09 '19 at 04:07