The C++ standard prohibits declaring types or defining anything in namespace std
, but it does allow you to specialize standard STL templates for user-defined types.
Usually, when I want to specialize std::swap
for my own custom templated type, I just do:
namespace std
{
template <class T>
void swap(MyType<T>& t1, MyType<T>& t2)
{
t1.swap(t2);
}
}
...and that works out fine. But I'm not entirely sure if my usual practice is standard compliant. Am I doing this correctly?
What you're doing is an overload and not a template specialization. The standard does not allow you to overload inside
namespace std
(17.6.4.2.1 §1)Therefore, prefer to put your template type into your own namespace and define a non-member
swap()
within that namespace (this is not strictly necessary, but good practice). This wayswap(x,y)
will work from anywhere via argument dependent lookup (ADL, aka Koenig lookup), ifx
ory
are in your namespace.Code using
swap()
should normally use theusing namespace std
technique. This way your version of swap will be found by ADL and it will be prefered to thestd::swap()
function, since it is more specialized.