Templates

Actually, there is a built-in Template swap function. It is much simpler to use that instead of writing our own.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<string>
using namespace std;
template <class T>
void show3(T a,T b,T c) {
  cout<<a<<","<<b<<","<<c<<endl;
}
template <class T>
void sort3(T& a,T& b, T& c) {
  if(a>b) swap(a,b);
  if(b>c) swap(b,c);
  if(a>b) swap(a,b);
}//sort3

int main() {
   int x=20,y=5,z=3;
   sort3(x,y,z);
   show3(x,y,z);
   double d1=5.5, d2=-20, d3=0.25;
   sort3(d1,d2,d3);
   show3(d1,d2,d3);
   string name1="Mary", name2="Bill", name3="Jay";
   sort3(name1,name2,name3);
   show3(name1,name2,name3);
   system("pause");
   return 0;
}//main
CODE
3,5,20
-20.0,25.5,5.5
Bill,Jay,Mary
Press any key to continue . . .

Notice the show3 function does not use pass by reference. We only need to use pass by reference when we need to change the values of the arguments.

NEXT: Finding a total