Write a program to swap the contents of two variables. Use
template variables as function arguments.
#include <iostream>
using namespace std;
template<typename T>
void swap(T* number1, T* number2) {
T temp= *number1;
*number1 = *number2;
*number2 = temp;
}
int main() {
// initialize variables
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function by passing by values
cout << "\nAfter swapping" << endl;
swap<int>(&a,&b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
char k = 'a', l = 'b';
cout << "\n\nBefore swapping" << endl;
cout << "k = " << k << endl;
cout << "l = " << l << endl;
// call function by passing by values
cout << "\nAfter swapping" << endl;
swap<char>(&k,&l);
cout << "k = " << k << endl;
cout << "l = " << l << endl;
cin>>a;
return 0;
}
Comments
Leave a comment