DS 03 Using Templates in C++
DS 03 Using Templates in C++
Video Lecture
Lecture No. 3
Using Templates in C++
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chis
hti International Islamic University H-10, Islamabad, Pakistan
C++ Class Templates
Templates are powerful features of C++ which allows us to write generic
programs. There are two ways we can implement templates:
Function Templates
Class Templates
Class templates come in handy as they can make our code shorter and more
manageable.
Example 1: Function Overloading
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int iA = 3, iB = 4;
double dA = 3.4, dB = 4.3;
cout << iA << " + "<< iB << " = " << add(iA, iB) << endl;
cout << dA << " + " << dB << " = " << add(dA, dB) << endl;
system("PAUSE");
return 0;
}
3 1
Example 2: Function Template
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int iA = 3, iB = 4;
double dA = 3.4, dB = 4.3;
cout << iA <<" + "<< iB << " = "<< add(iA, iB) << endl;
cout << dA <<" + " << dB << " = " << add(dA, dB) << endl;
system("PAUSE");
return 0;
}
4 1
Example 3: Class Template (1/2)
#include <iostream>
#include <stdlib.h>
using namespace std;
T add();
T divide();
};
5 1
Example 3: Class Template (2/2)
template <typename T> T Calculator<T> :: add() {
return num1 + num2;
}
int main() {
Calculator <int> iCalc(5, 2);
Calculator <double> dCalc(2.6, 1.2);
cout << "Int Result:" << endl;
iCalc.Result();
system("PAUSE");
return 0;
}
6 2
Example 4: Using Two Templates in a Class (1/2)
#include <iostream>
#include <stdlib.h>
using namespace std;
7 1
Example 4: Using Two Templates in a Class (2/2)
template<class T1, class T2> void Test_Class <T1,T2> :: Test(T1 x, T2 y) {
a = x;
b = y;
}
template<class T1, class T2> void Test_Class <T1,T2> :: Show() {
cout << a << " and " << b << endl;
}
int main() {
Test_Class <double,int> test1 (1.23, 123);
Test_Class <int,char> test2 ( 200, 'Z');
test1.Show();
test2.Show();
system("PAUSE");
return 0;
}
8 2