In: Computer Science
Write a function template sort that takes two references to generic objects and switches them if the first argument is larger than the second. It is only assumed that operator<() and a default constructor are defined for the objects considered.
main.cpp
#include <iostream>
using namespace std;
template <typename T>
void templateSort(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1,i2;
cout<<"Enter two integer : ";
cin>>i1>>i2;
cout<<endl;
cout << "Before passing data to function
template.\n";
cout << "i1 = " << i1 << "\ni2 = "
<< i2;
if(i1>i2){
templateSort(i1, i2);
}
cout << "\n\nAfter
passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = "
<< i2;
return 0;
}
Output:-
Enter two integer : 10 5 Before passing data to function template. i1 = 10 i2 = 5 After passing data to function template. i1 = 5 i2 = 10