Templates and Generic Programming
Template is a new concept that enables us to define generic classes and functions
and thus provides support for generic programming.
A template can be used to create family of classes or functions.for eg:a class
templates for an array class would enable us to create arrays of various data types
om
such as int array or float array or char array.
Generic programming is an approach where generic types are used as parameters
in algorithms so that they work for a variety of suitable data types and data
.c
structures.
t
po
Advantages and Disadvantages of using templates
Advantages: gs
lo
Class Template can handle different types of parameters.
A template can be used to create family of classes or functions.
.b
Compiler generates classes for only the used types.
eb
Templates reduce the effort on coding for different data types to a single set
of code.
Testing and debugging efforts are reduced.
ew
Disadvantages:
od
Some compilers exhibited poor support for templates.So,the use of
dc
templates could decrease code portability.
Because a template by its nature exposes its implementation,so its use in
m
large systems can lead to longer build times.
Templates are in the headers,which require a complete rebuild of all
project pieces when changes are made.
Types of Template
There are basically two types of template.They are:
1 Compiled by Er.Shraddha Parajuli
1. Function Template
2. Class Template
1)Function Template:It is used to create a family of functions with different
argument types.for eg:we can define a template for a function,say mul() that would
helps us to create various version of mul() for multiplying int,float and double type
om
values.
a)Function template with single parameter:
.c
General Format
t
po
template<class T>
return-type function-name(argument list of type T){
//body of the function with type T gs
lo
}
.b
Eg:WAP to calculate the sum of two integers and two float values using function
template.
eb
Ans: #include<iostream>
ew
using namespace std;
template<class T>
od
T add(T x,T y){
dc
return (x+y);
m
}
main(){
int a=2,d=3;
float b=2.3,c=6.2;
cout<<"sum of int and int values="<<add(a,d)<<endl;
2 Compiled by Er.Shraddha Parajuli
cout<<"sum of float and float values="<<add(b,c);
return 0;
}
Q1)WAP to find the greatest among two integers and two float variable using
function template.
om
Ans: #include <iostream>
using namespace std;
.c
template <class T>
t
po
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2; gs
lo
}
.b
int main()
{
eb
int i1, i2;
ew
float f1, f2;
cout << "Enter two integers:";
od
cin >> i1 >> i2;
dc
cout <<" larger value among two integers."<< Large(i1, i2) << endl;
cout << "Enter two floating-point numbers:";
m
cin >> f1 >> f2;
cout << " the larger value among two float."<<Large(f1, f2)<< endl;
return 0;
}
3 Compiled by Er.Shraddha Parajuli
Q3)WAP to swap the values of two integers as a=100 and b=200 and two float
values as c=100.2 and d=98.6 using function template.
Ans: #include<iostream>
using namespace std;
template<class T>
om
void swapp(T &x,T &y){
T temp;
.c
temp=x;
t
po
x=y;
y=temp;
} gs
lo
main(){
.b
int a=100,b=200;
float c=100.2,d=98.6;
eb
swapp(a,b);
ew
cout<<"after swapping intergers value:"<<endl<<"a="<<a<<"b="<<b<<endl;
swapp(c,d);
od
cout<<"after swapping float values:"<<endl<<"c="<<c<<"d="<<d;
dc
}
Q4)Write a function template to find average and multiplication of numbers.
m
Ans: #include<iostream>
using namespace std;
template <class T>
void calculate(T x,T y){
T s;
4 Compiled by Er.Shraddha Parajuli
s=(x+y)/2;
cout<<"average of two numbers="<<s;
T m;
m=x*y;
om
cout<<"multiplication of two numbers="<<m;
}
.c
main(){
t
po
int a=2, b=3;
calculate(a,b);
} gs
lo
Q4)WAP to find the maximum among the elements of an integer array having 6
.b
elements and array of float having 4 elements using function template.
Ans: #include<iostream>
eb
using namespace std;
ew
template<class T>
T min(T a[], int n)
od
{
dc
int i, j;
T temp=a[0];
m
for(i=0;i<n;i++)
{
if(a[i]>temp)
temp=a[i];
}
5 Compiled by Er.Shraddha Parajuli
return temp;
}
main()
{
int min1;
om
float min2;
int a[6]={5,2,1,3,4,0};
.c
float b[4]={1.2,8.3,6.7,1.1};
t
po
min1= min(a,6);
cout<<"\nminimum of integer array: "<<min1;
min2=min(b,4); gs
lo
cout<<"\nminimum of float array: "<<min2;
.b
return 0;
eb
Bubble sorting using function template
ew
#include<iostream>
od
using namespace std;
template<class T>
dc
void bubble(T a[], int n)
m
{
int i, j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
6 Compiled by Er.Shraddha Parajuli
{
if(a[i]>a[j])
{
T temp;
temp = a[i];
om
a[i] = a[j];
a[j] = temp;
.c
}
t
po
}
}
} gs
lo
.b
main()
eb
{
int i;
ew
int a[6]={5,2,1,3,4,0};
od
float b[4]={1.2,8.3,6.7,1.1};
bubble(a,6);
dc
cout<<"\nSorted Order Integers: ";
m
for( i=0;i<6;i++)
{
cout<<a[i]<<"\t";
}
bubble(b,4);
7 Compiled by Er.Shraddha Parajuli
cout<<"\nSorted Order floats: ";
for( i=0;i<4;i++){
cout<<b[i]<<"\t";
}
return 0;
om
}
b)Function template with multiple parameters(i.e. function with different generic
.c
types):
t
po
We can use more than one generic data type in template statement,using a
comma-separated list.i.e.
General Format
template<class T,class T2,……..>
gs
lo
return-type function-name(argument of types T1,T2,….){
.b
//body of function
eb
}
ew
Eg:WAP to find the sum of int,float values and float,int values.
Ans: #include<iostream>
od
using namespace std;
dc
template<class T1,class T2>
void add(T1 x,T2 y){
m
cout<<"sum="<<x+y;
}
main(){
int a=2,d=3;
float b=2.3,c=6.2;
8 Compiled by Er.Shraddha Parajuli
cout<<"sum of int and float values="<<add(a,b);
cout<<"sum of float and int values="<<add(c,d);
return 0;
}
Q1)WAP to find the greatest among int ,float values and float,int values using
om
function template.
Ans: #include <iostream>
.c
using namespace std;
t
po
template <class T1,class T2>
void Large(T1 n1, T2 n2)
{ gs
lo
if(n1>n2)
.b
cout<<"largest is:"<<n1;
else
eb
cout<<"largest is:"<<n2;
ew
}
int main()
od
{
dc
int i1, i2;
float f1, f2;
m
cout << "Enter a integer and float value:";
cin >>i1>>f1;
Large(i1, f1);
cout << "Enter a float and integer value:";
cin >> f2 >> i2;
9 Compiled by Er.Shraddha Parajuli
Large(f2, i2);
return 0;
}
***Use of nesting of function template is shown in the given example:
om
Eg:Bubble sorting using nesting of function template
#include<iostream>
.c
using namespace std;
t
po
template<class T>
void bubble(T a[], int n)
{ gs
lo
int i, j;
.b
for(i=0;i<n-1;i++)
eb
{
for(j=i+1;j<n;j++)
ew
{
od
if(a[i]>a[j])
{
dc
swap(a[i],a[j]);
m
}
}
}
}
template<class X>
10 Compiled by Er.Shraddha Parajuli
void swap(X &a,X &b){
X temp;
temp=a;
a=b;
b=temp;
om
}
main()
.c
{
t
po
int i;
int a[6]={5,2,1,3,4,0};
float b[4]={1.2,8.3,6.7,1.1}; gs
lo
bubble(a,6);
.b
cout<<"\nSorted Order Integers: ";
eb
for( i=0;i<6;i++)
cout<<a[i]<<"\t";
ew
bubble(b,4);
od
cout<<"\nSorted Order floats: ";
for( i=0;i<4;i++)
dc
cout<<b[i]<<"\t";
m
return 0;
}
Overloading of template functions:
A function template can be overloaded either by template function or by the
ordinary functions of its name.
An error is generated if no match is found.
11 Compiled by Er.Shraddha Parajuli
Eg: #include<iostream>
using namespace std;
template<class T>
void display(T x){
cout<<"value of template x="<<x;
om
}
template<class T,class T1>
.c
void display(T x,T1 y){
t
po
cout<<"value of x1="<<x<<"value of y1="<<y;
}
void display(int x){ gs
lo
cout<<"value of normal function x="<<x;
.b
}
eb
main(){
display(100);
ew
display(12.2);
od
display(12,13.4);
dc
}
m
Output:
Value of normal function x=100
Value of template function x=12.2
Value of x=12,y=13.4
12 Compiled by Er.Shraddha Parajuli
2)Class Template
Class template with single parameter:
General Format:
template<class T>
class class-name{
om
//class member specifications with type T
}
.c
The class template is very similar to the ordinary class definition except the prefix
t
po
template<class T> and the use of T.This prefix tells the compiler that we are going
to declare a template and use T as a typename in the declaration.
gs
A class created from a class template is called a template class.The syntax for
declaring an object of template class is:
lo
Class-name<type>object-name;
.b
This process of creating a specific object from a class template is known as
eb
instantiation.
Syntax for defining the member function of class template outside the class:
ew
template<class T>
od
return-type class-name<T>::function-name(argumentlist with T){
//body of the function
dc
}
m
Eg:WAP to calculate the sum of two integers and two float values using class
template.
Ans: #include<iostream>
using namespace std;
template<class T>
class demo{
13 Compiled by Er.Shraddha Parajuli
T x,y;
public:
demo(T a,T b){
x=a;
y=b;
om
}
void display(){
.c
cout<<"sum="<<x+y;
t
po
}
};
main(){ gs
lo
demo<int>d1(1,2);
.b
d1.display();
eb
demo<float>d2(2.2,3.2);
d2.display();
ew
}
od
Q1)WAP to find out the greatest among the two integer values and two float
dc
values using class template.
Ans: #include<iostream>
m
using namespace std;
template<class T>
class demo{
T x,y;
public:
14 Compiled by Er.Shraddha Parajuli
demo(T a,T b){
x=a;
y=b;
}
void display(){
om
cout<<"greatest="<<(x>y?x:y);
}
.c
};
t
po
main(){
demo<int>d1(1,2);
d1.display(); gs
lo
demo<float>d2(2.2,3.2);
.b
d2.display();
eb
}
Q2)WAP to find the scalar product of two vectors in which both vector are of int
ew
type.
Ans: First Method:
od
#include<iostream>
dc
using namespace std;
int size=3,i;
m
template<class T>
class vector{
T *v;
public:
vector(){
15 Compiled by Er.Shraddha Parajuli
v=new T[size];
for(i=0;i<size;i++){
v[i]=0;
}
}
om
vector(T a[]){
for(i=0;i<size;i++){
.c
v[i]=a[i];
t
po
}
}
T operator *(vector y){ gs
lo
T sum=0;
.b
for(i=0;i<size;i++){
eb
sum+=v[i]*y.v[i];
}
ew
return sum;
od
}
void display(){
dc
for(i=0;i<size;i++){
m
cout<<v[i]<<" ";
}
}
};
main(){
16 Compiled by Er.Shraddha Parajuli
int x[3]={1,2,3};
int y[3]={4,5,6};
vector<int>v1;
vector<int>v2;
v1=x;
om
v2=y;
v1.display();
.c
v2.display();
t
po
cout<<"scalar product of two vector i.e v1*v2="<<v1*v2;;
} gs
lo
OR Second Method:
.b
#include<iostream>
eb
using namespace std;
template<class T>
ew
class scalar{
od
T a,b,c;
public:
dc
scalar(){
m
}
scalar(T x,T y,T z){
a=x;
b=y;
17 Compiled by Er.Shraddha Parajuli
c=z;
}
T operator *(scalar p){
T temp;
temp=a*p.a+b*p.b+c*p.c;
om
return temp;
.c
}
t
po
void display(){
cout<<a<<"i+"<<b<<"j+"<<c<<"k"<<endl;
} gs
lo
};
.b
main(){
eb
int s3;
scalar<int>s1(1,2,3);
ew
s1.display();
od
scalar<int>s2(2,3,4);
s2.display();
dc
s3=s1*s2;
m
cout<<"scalar product="<<s3;
}
Q3)WAP to find the scalar product of two float type vectors using class template.
Ans: #include<iostream>
using namespace std;
18 Compiled by Er.Shraddha Parajuli
int size=3,i;
template<class T>
class vector{
T *v;
public:
om
vector(){
v=new T[size];
.c
for(i=0;i<size;i++){
t
po
v[i]=0;
}
} gs
lo
vector(T a[]){
.b
v=new T[size];
eb
for(i=0;i<size;i++){
v[i]=a[i];
ew
}
od
}
T operator *(vector y){
dc
T sum=0;
m
for(i=0;i<size;i++){
sum+=v[i]*y.v[i];
}
return sum;
}
19 Compiled by Er.Shraddha Parajuli
void display(){
for(i=0;i<size;i++){
cout<<v[i]<<" ";
}
}
om
};
main(){
.c
float x[3]={1,2,3};
t
po
float y[3]={4,5,6};
vector<float>v1;
vector<float>v2; gs
lo
v1=x;
.b
v2=y;
eb
v1.display();
v2.display();
ew
cout<<"scalar product of two vector i.e v1*v2="<<v1*v2;;
od
}
Q)A program to push and pop element in a stack using class template.
dc
Ans: #include<iostream>
m
using namespace std;
#define max 5
int i;
template<class T>
class stack{
20 Compiled by Er.Shraddha Parajuli
T stk[max];
int top;
public:
stack(){
top=-1;
om
}
void push(T data){
.c
if(top==(max-1)){
t
po
cout<<"stack is full";
}
else{ gs
lo
top++;
.b
stk[top]=data;
eb
}
}
ew
void pop(){
od
if(top==-1){
cout<<"stack is empty";
dc
}
m
else{
top--;
}
}
void show(){
21 Compiled by Er.Shraddha Parajuli
for(i=top;i>=0;i--){
cout<<" "<<stk[i]<<" ";
}
}
};
om
main(){
stack<int>s;
.c
s.push(1);
t
po
s.push(2);
s.push(3);
s.push(4); gs
lo
s.push(5);
.b
s.show();
eb
s.pop();
s.show();
ew
}
od
Class template with multiple parameters:
dc
We can use more than one generic data types in a class template.
m
They are declared as comma-separated list within template specification as shown
below:
template<class T1,class T2,…… >
class class-name{
//body of class
}
22 Compiled by Er.Shraddha Parajuli
Eg:A program to find the sum of int,float and float,int values using class template.
Ans: #include<iostream>
using namespace std;
template<class T1,class T2>
class demo{
om
T1 a;
T2 b;
.c
public:
t
po
demo(T1 x,T2 y){
a=x;
b=y; gs
lo
}
.b
void display(){
eb
cout<<"sum="<<a+b;
}
ew
};
od
main(){
int a,b;
dc
float c,d;
m
cout<<"enter two integers:";
cin>>a>>b;
cout<<"enter two float values:";
cin>>c>>d;
demo<int,float>obj(a,c);
23 Compiled by Er.Shraddha Parajuli
obj.display();
demo<float,int>obj1(d,b);
obj1.display();
}
om
**Using default type in a class template**
Eg: #include<iostream>
.c
using namespace std;
t
po
template<class T1=int,class T2=int>
class demo{
T1 a; gs
lo
T2 b;
.b
public:
eb
demo(T1 x,T2 y){
a=x;
ew
b=y;
od
}
void display(){
dc
cout<<"sum="<<a+b;
m
}
};
main(){
int a=2,b=5;
float c=1.1,d=2.2;
24 Compiled by Er.Shraddha Parajuli
demo<int,int>obj(a,c);
obj.display();
demo<float,int>obj1(d,b);
obj1.display();
demo< >obj3(a,c);
om
obj3.display();
demo<float>obj4(c,a);
.c
obj4.display();
t
po
}
Output:
Sum=3 gs
lo
Sum=7.2
.b
Sum=3
eb
Sum=3.1
ew
Exception Handling
od
Problems other than the logic and syntax error is exception.Exception is defined
as the run time anomalies or unusual conditions that a program may encounter
dc
while executing eg:division by zero,acces to an array outside of its bounds or
running out of memory or disk space.
m
When a program encounters an exceptional conditions ,it is important that it is
identified and dealt effectively.To deal with such anomalies/conditions special
feature is used which is termed as exception.
Types of exception
There are two types of exception as listed below:
25 Compiled by Er.Shraddha Parajuli
a)Synchronous exception:Errors such as “out-of range” index and overflow
belongs to synchronous exception.
b)Asynchronous exception:Errors caused by events beyond the control of
program such as keyboard interrupts belongs to asynchronous exception.
The purpose of exception handling mechanism is to provide means to detect and
report an exceptional circumstance so that appropriate action can be taken.
om
Exception handling mechanism includes following steps:
1. Find the problem(Hit the exception)
.c
2. Inform that the error has occurred(throw the exception)
t
3. Receive the error information(catch the exception)
po
4. Take corrective action(handle the exception)
gs
Exception handling/Error handling mechanism contains two segments:
1. To detect errors and to throw the exceptions.
lo
2. To catch the exceptions and take appropriate actions.
.b
Exception Handling mechanism
eb
This mechanism is basically built upon three keywords namely try,throw and
catch.The block of statements that may generate the exceptions are included
ew
within the braces of try block.When an exception is detected it is thrown
using a throw statement in the try block.
A catch block defined by the keyword catch catches the exception thrown by
od
the throw statement in the try block and handles it properly.
The catch block that catches an exception must immediately follow the try
dc
block that throws the exceptions.
m
26 Compiled by Er.Shraddha Parajuli
try block
Detects and thr
ows an except
ion
om
exception entity
t .c
po
Catch block
Catches and ha
ndles the excep
tion
gs
lo
.b
General form of try-catch block is:
eb
try{
…….
ew
throw (exception)
…….
od
…….}
catch(type argument){
dc
……
…..}
m
When the try block throws an exception,the program control leaves the try
block and enters the catch statement of the catch block.
Note:::
The exception are the objects used to transmit information about a
problem.If the type of the object thrown matches the argument type in the
catch statement then catch block is executed for handling the exception.If
27 Compiled by Er.Shraddha Parajuli
they donot match,the program is aborted with the help of abort() function
which is invoked by default(i.e. automatically by the compiler).
When the exception is detected and thrown ,the control goes to statement
immediately after the catch block.
Eg:main(){
om
int a,b,x;
cout<<”enter a and b:”;
.c
cin>>a>>b;
x=a-b;
t
po
try{
if(x!=0)
{
cout<<”result=”<<a/x;
}
gs
lo
else{
.b
throw(x);
}
eb
}
catch(int i){
ew
cout<<”exception caught:divide by zero”;
}
od
}
dc
Most often the exceptions are thrown by functions that are from within try
blocks.The point at which throw is executed is called the throw point.
m
General format for this kind of exception is:
return-type function-name(argument list){
….
throw(object)
…
}
try{
…..
28 Compiled by Er.Shraddha Parajuli
Call/invoke function here
}
catch(type argument){
….
Handles exception here
}
Eg:
om
void divide (int x,int y,int z)
{
.c
if((x-y)!=0){
cout<<”result=”<<z/(x-y);
t
po
}
else{
throw (x-y);
}
}
gs
lo
main(){
.b
try{
divide(10,20,30);
eb
divide(10,10,20);
}
ew
catch(int i){
cout<<”caught an exception”;
od
}
}
dc
Multiple catch statement:
m
When a program segment has more than one condition to throw an
exception,in such cases multiple catch statements with a try statement is
used.Syntax:
try{
//try block
}
catch(type1 argument){
//catch block1
29 Compiled by Er.Shraddha Parajuli
}
catch(type2 argument){
//catch block2
}
…………….
…………….
catch(typeN argument){
om
//catch blockN
}
.c
When an exception is thrown the catch block is searched in order for an
appropriate match.The first handler that yields a match is executed .After
t
po
executing the handler block(i.e. catch),the control goes to the first statement
after the last catch block for that try(in other words,all other handlers are
skipped).When no match is found ,program is terminated.
Eg: gs
lo
void test(int x){
.b
try{
eb
if(x==1)
throw x;
ew
else if(x==0)
od
throw ‘x’;
else
dc
throw 1.2;
m
}
catch(int m){
cout<<”caught an integer”;
}
Catch(char c){
30 Compiled by Er.Shraddha Parajuli
cout<<”caught a character”;
}
catch(float d){
cout<<”caught a float value”;
}
om
}
main(){
.c
cout<<”testing multiple catches:”;
t
po
test(1);
test(0);
test(-1); gs
lo
}
.b
eb
Rethrowing an exception
ew
A catch block can also decide to rethrow the exception caught without processing
it.In such situations we may simply invoke throw without any arguments as shown
below:
od
void divide(float x,float y){
dc
try{
If(y==0.0)
m
throw y;
else
cout<<”division:”<<x/y;
}
catch(float a){
31 Compiled by Er.Shraddha Parajuli
cout<<”caught float “;
throw;//rethrows exception
}
}
main(){
om
try{
divide(10.5,2.0);
.c
divide(20.0,0.0);
t
po
}
catch(float b){
cout<<”caught exception”; gs
lo
}
.b
}
eb
When an exception is rethrown ,it will not be caught by the same catch statement
or any other catch in that group.Rather,it will be caught by an appropriate catch in
ew
the outer try/catch sequence only.
od
Standard Template Library(STL)
dc
The collection of general-purpose templatized classes(data structures)and
functions(algorithms)that could be used as a standard approach for storing and
m
processing of data is known as standard template library(STL).
STL are defined under the directive using namespace std.
Components of STL
1. Containers
2. Algorithms
3. Iterators
32 Compiled by Er.Shraddha Parajuli
Algorithm algorithm
1 2
Iterator 1 Iterator 2
Object1
om
.c
Object2 object3
t
po
Iterator 3
gs
lo
.b
algorithm
3
eb
Fig:relationship between three STL components.
ew
od
1)Containers:A container is an object that actually stores data.It is a way data is
organized in memory.The STL containers are implemented by template classes and
dc
therefore can be easily customized to hold different types of data.The STL defines
10 containers which are grouped into 3 categories as given below:
m
Sequeunce containers:This container stores elements in a linear
sequence.Each element is related to other elements by its position
along the line.Eg:vector,list,deque.
Associative containers:These are designed to support direct access to
elements using keys.They are not sequential .There are four types of
associative containers they are set,multiset,map,multimap.All these
containers stores data in a structure called tree which facilitate fast
33 Compiled by Er.Shraddha Parajuli
searching,deletion and insertion.But these are very slow for random
access and inefficient for storing.
Derived containers:These are the containers derived from different
sequence containers.These are also known as container
adaptors.This donot support iterators and so we cannot use them for
manipulation .It support two member function push() an pop() for
deleting and inserting elements.There are three types of derived
om
containers they are stack,queue,priority-queue.
2)Algorithms:Algorithms are functions that can be used generally across a variety
.c
of containers for processing their contents.STL provides more than 60 standard
t
algorithms to support more extended or complex operations.It allows us to work
po
with two different type of containers at the same time.To access standard
algorithm we must include<algorithm>in our program.STL algorithms,based on the
gs
nature of operations they perform,it is categorized as:
Retrieve or nonmutating algorithms.
lo
Mutating algorithms
.b
Sorting algorithms
eb
Set algorithms
Relational algorithms
ew
3)Iterators:Iterators behave like pointers and are used to access container
elements.They are often use to go from one element to another,a process known
od
as iterating through the container.There are five types of iterators they
are:input,output,forward,bidirectional,random.Each type of iterator is used for
dc
performing certain actions.The input and output supports the least functions.They
can be used only to traverse in container.The forward iterator supports all the
functions of input and output and also retains its position in the container.A
m
bidirectional iterator,while supporting all forward iterator operations,provides the
ability to move in the backward direction in the container.A random access iterator
combines the functionality of a bidirectional iterator with the ability to jump to an
arbitrary location.
34 Compiled by Er.Shraddha Parajuli
om
t .c
po
gs
lo
.b
eb
ew
od
dc
m
35 Compiled by Er.Shraddha Parajuli