Simple example of Template in C++.
1: #include <iostream>
2: using namespace std;
3: template <class dT>
4: void swapIt(dT &u, dT &v);
5:
6: int main(){
7: int i1 = 2, i2 = 4;
8: double d1 = 2.2, d2 = 5.6;
9: float f1 = 1.1, f2 = 5.2;
10: char c1 = 'c', c2 = 'R';
11: cout << "i1 = " << i1 << "\ti2 = " << i2 << endl;
12: cout << "d1 = " << d1 << "\td2 = " << d2 << endl;
13: cout << "f1 = " << f1 << "\tf2 = " << f2 << endl;
14: cout << "c1 = " << c1 << "\tc2 = " << c2 << endl;
15:
16: swapIt(i1,i2);
17: swapIt(f1,f2);
18: swapIt(d1,d2);
19: swapIt(c1,c2);
20:
21: cout << "\nAfter swaping: " << endl;
22: cout << "i1 = " << i1 << "\ti2 = " << i2 << endl;
23: cout << "d1 = " << d1 << "\td2 = " << d2 << endl;
24: cout << "f1 = " << f1 << "\tf2 = " << f2 << endl;
25: cout << "c1 = " << c1 << "\tc2 = " << c2 << endl;
26: return 0;
27: }
28: template <class dT>
29: void swapIt(dT &u, dT &v){
30: dT t = u;
31: u = v;
32: v = t;
33: }
No comments:
Post a Comment