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

那年仲夏 提交于 2020-01-13 03:03:13

问题


Possible Duplicate:
how to provide a swap function for my class?

There are some questions about this, but a lot of contradictions (person A giving solution A' with many upvotes with person B saying it's UB) or "only works if the compiler supports ADL" is answered.

So, say I have the following template (container) class:

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

then what is the correct way to make sure this (example) code works:

C<int> x, y;
std::swap(x, y);

Please give your answer for C++03, and if it still works in C++0x, even better!


回答1:


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



来源:https://stackoverflow.com/questions/6414196/how-to-add-stdswap-for-my-template-class

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