Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

class

stl

swap

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!

like image 445
orlp Avatar asked Jun 20 '11 16:06

orlp


1 Answers

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

like image 200
Macke Avatar answered Oct 13 '22 10:10

Macke