Design a template function for swapping the int, double and char type values between two variables. Note: Use function overloading.
#include <iostream>
using namespace std;
template <class T>
void SWAP_T(T& first, T& second)
{
T temp(first);
first = second;
second = temp;
}
void SWAP(int& i, int& j)
{
int temp = i;
i = j;
j = temp;
}
void SWAP(double& i, double& j)
{
double temp = i;
i = j;
j = temp;
}
void SWAP(char& i, char& j)
{
char temp = i;
i = j;
j = temp;
}
int main()
{
int a = 10;
int b = 20;
cout << a << " " << b << endl;
cout << "SWAP()" << endl;
SWAP(a, b);
cout << a << " " << b << endl << endl;
double c = 10.5;
double d = 200.6;
cout << c << " " << d << endl;
cout << "SWAP()" << endl;
SWAP(c, d);
cout << c << " " << d << endl << endl;
char e = 'e';
char f = 'f';
cout << e << " " << f << endl;
cout << "SWAP()" << endl;
SWAP(e, f);
cout << e << " " << f << endl << endl;
return 0;
}
Comments
Leave a comment