Function Overloading and Template Example
1 // Function Overloading and Template Example
2 #include <iostream.h>
3
4 // function prototypes
5 int sqr(int);
6 int sqr(float);
7
8 // Template definition
9
10 template <class Q>
11 Q mysqr(Q x) {
12 cout << "this is the function template" << endl;
13 return x * x;
14 }
15
16 int main() {
17 cout << "sqr((float) 2.2)=" << sqr((float) 2.2) << endl; // sqr w/float
18 cout << "sqr((int) 2.2)=" << sqr((int) 2.2) << endl; // sqr w/int
19 cout << "mysqr((int) 2.2)=" << mysqr((int) 2.2) << endl; // template w/int
20 cout << "mysqr((double) 2.2)=" << mysqr((double) 2.2) << endl;// template with
21 return 0; // double
22 }
23
24 // define the sqr function with an int parameter
25
26 int sqr(int x) {
27 cout << "this is the function with parameter int" << endl;
28 return x * x;
29 }
30
31 // define the sqr function with a float parameter
32
33 int sqr(float x) {
34 cout << "this is the function with parameter float" << endl;
35 return x * x;
36 }
37
38 // output should be
39 // this is the function with parameter float 4.84
40 // this is the function with parameter int 4
41 // this is the function template 4
42 // this is the function template 4.84
43
source sode here.