#include <iostream>
struct H
{
void swap(H &rhs);
};
void swap(H &, H &)
{
std::cout << "swap(H &t1, H &t2)" << std::endl;
}
void H::swap(H &rhs)
{
using std::swap;
swap(*this, rhs);
}
int main(void)
{
H a;
H b;
a.swap(b);
}
And this is the result:
swap(H &t1, H &t2)
In the code above, I try to define a swap function of H
. In the function void H::swap(H &rhs)
, I use an using declaration to make the name std::swap visible. If there isn't an using declaration, the code cannot be compiled because there is no usable swap function with two parameters in class H
.
I have a question here. In my opinion, after I used the using declaration -- using std::swap
, it just make the std::swap -- the template function in STL visible. So I thought that the swap in STL should be invoked in H::swap()
. But the result showed that the void swap(H &t1, H &t2)
was invoked instead.
So here is my question:
- Why can't I invoke swap without a using declaration?(I guess it is because there is no swap function with two parameters in the class. But I am not sure. )
- Why will the swap of my definition be invoked instead of the STL swap in the
H::swap
?