Templates

Let's do something a bit more useful. Here we have a Template function that will sort 3 values.

Because we are using pass by reference to sort the 3 values, we CAN NOT use literal values, we MUST use variables.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#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 and b
   T temp;
    temp=a;
    a=b;
    b=temp;
  }//swap a and b
  if(b>c) { //swap b and c
   T temp;
    temp=b;
    b=c;
    c=temp;
  }//swap b and c
  if(a>b) { //swap a and b
	T temp;
    temp=a;
    a=b;
    b=temp;
  }//swap a and b
}//sort3

int main() {
   int x=20,y=5,z=3;
   sort3(x,y,z); //T is int
   show3(x,y,z);
   double d1=5.5, d2=-20, d3=0.25;
   sort3(d1,d2,d3); //T is double
   show3(d1,d2,d3);
   string name1="Mary", name2="Bill", name3="Jay";
   sort3(name1,name2,name3); //T is string
   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 that when we write the swap, we declare temp to be type T.

NEXT: Using swap