How to add std::swap for my template class? [duplicate]

☆樱花仙子☆ 提交于 2019-12-04 07:23:32

You are not allowed to overload functions in the std-namespace.

Declare swap as a free function, overloaded in the same namespace as your class C:

 template<class T>
 void swap(C<T>& x, C<T>& y) { x.swap(y); }

The right way to swap is to import std::swap and use a non-qualified version (which is retreieved via namespace-based Koenig lookup):

 template<class T>
 void dostuff(T x, T y) {
    ...
    using std::swap;
    swap(x,y);
    ...
 }

That will use C::swap if x and are C, and std::swap for types that do not have their own swap.

(The import of std::swap like above is only necessary in template functions where the type is not known. If you know you have a C, then you can use x.swap(y) right away w/o problems.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!