// L-10 MCS 360 Wed 5 Feb 2020 : templated_swap.cpp

/* We introduce generic programming with a swap for any type T.
   Our function was called "MySwap" in order not to confuse
   with the swap of the STL algorithms. */

#include <iostream>
#include <string>

using namespace std;

template <typename T>
void MySwap ( T& x, T& y); // swaps x with y

int main()
{
   cout << "swapping two integers..." << endl;
   int a = 2; int b = 3;
   cout << "before swap : a = " << a;
   cout << ", b = " << b << endl;
   MySwap<int>(a,b); // observe passing of type int
   cout << " after swap : a = " << a;
   cout << ", b = " << b << endl;

   cout << "swapping two strings..." << endl;
   string s = "hello"; string t = "there";
   cout << "before swap : s = " << s;
   cout << ", t = " << t << endl;
   MySwap<string>(s,t); // observe passing of type string
   cout << " after swap : s = " << s;
   cout << ", t = " << t << endl;
   
   return 0;
}

template <typename T>
void MySwap ( T& x, T& y)
{
   T z = x; // z acts as swap buffer

   x = y;   // copy y to x, z holds x
   y = z;   // copy z to y
}
