homer512

swap

Dec 4th, 2013
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <vector>
  2. // using std::vector
  3. #include <utility>
  4. // using std::swap
  5.  
  6. namespace ns {
  7.     struct Obj {
  8.         /* some pseudo-data */
  9.         std::vector<int> data;
  10.         int x;
  11.         /* define member function to do the actual swapping */
  12.         void swap(Obj& b) {
  13.             using std::swap;
  14.             /* never call std::swap(a,b), always import std::swap with using,
  15.              * then let the lookup rules figure out which swap specialization
  16.              * to call
  17.              */
  18.             swap(this->data, b.data);
  19.             swap(this->x, b.x);
  20.         }
  21.     };
  22.     /* define swap in the same namespace as your class */
  23.     void swap(Obj& a, Obj&b) {
  24.         a.swap(b);
  25.     }
  26. }
  27. /* specialize std::swap unless your class is a template */
  28. namespace std {
  29.     template<>
  30.     void swap<ns::Obj>(ns::Obj& a, ns::Obj& b) {
  31.         a.swap(b);
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment