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);
}
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.