Write a program to swap two content of two variables using a template.
#include<iostream> using namespace std; template <typename T> void swap_var(T&,T&); int main() { int i1 = 45,i2 = 54; char c1 = 'A',c2 = 'a'; float f1 = 5.7,f2 = 7.5; cout << "before swapping " << endl; cout << "v1 = " << i1 << " v2 = " << i2 << endl; cout << "v1 = " << c1 << " v2 = " << c2 << endl; cout << "v1 = " << f1 << " v2 = " << f2 << endl; swap_var(i1,i2); swap_var(c1,c2); swap_var(f1,f2); cout << "after swapping " << endl; cout << "v1 = " << i1 << " v2 = " << i2 << endl; cout << "v1 = " << c1 << " v2 = " << c2 << endl; cout << "v1 = " << f1 << " v2 = " << f2 << endl; return 0; } template <typename T> void swap_var(T &x,T &y) { T temp; temp = x; x = y; y = temp; }
Output
before swapping v1 = 45 v2 = 54 v1 = A v2 = a v1 = 5.7 v2 = 7.5 after swapping v1 = 54 v2 = 45 v1 = a v2 = A v1 = 7.5 v2 = 5.7