C++ Template Example

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
#include <iostream>
using namespace std;

template<class T>
class math {
private:
T a;
T b;
public:
math(T a, T b);
T add();
T sub();
};

template<class T>
math<T>::math(T a, T b){
this->a = a;
this->b = b;
};
template<class T>
T math<T>::add(){
return a + b;
};
template<class T>
T math<T>::sub(){
return a - b;
};

int main(int argc, const char * argv[]) {
math<int> m1(10,5);
math<float> m2(2.5,0.5);
cout << m1.add() << endl << m1.sub() << endl;
cout << m2.add() << endl << m2.sub() << endl;
return 0;
}