4. Definition:
Templates are used to define generic definition of
functions or classes.
A template is not related to specific data types and
can work with different data types.
Can re-use same code with int, string, etc.
5. There are two types of templates:
Function templates
Class templates
6. Function templates are special functions that can
operate with generic types.
This allows us to create a function template whose
functionality can be adapted to more than one
type or class without repeating the entire code for
each type.
Same code is re-used for different types
8. Example:
#include<iostream.h>
#include<conio.h>
using namespace std;
template<class T>
void swap(T&x,T &y)
{
t temp=x;
x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"na and b before swaping
:"<<a<<"t"<<b;
swap(a,b);
cout<<"na and b after
swaping :"<<a<<"t"<<b;
cout<<"nnc and d before swaping
:"<<c<<"t"<<d;
swap(c,d);
cout<<"nc and d after
swaping :"<<c<<"t"<<d;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter A,B values(integer):";
cin>>a>>b;
cout<<"Enter C,D values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}
9. Output:
Enter A, B values (integer): 10 20
Enter C, D values (float): 2.50 10.80
A and B before swapping: 10 20
A and B after swapping: 20 10
C and D before swapping: 2.50 10.80
C and D after swapping: 10.80 2.50
10. Program:
#include<iostream>
#include<conio.h>
using namespace std;
template <class Type>
Type Max(Type a, Type b)
{
if(a>b)
return a;
else
return b;
}
Void main()
{
int n;
float m;
n=Max(10, 50);
cout<<“Maximum of two integers:“<<n<<endl;
m=Max(4.8, 2.2);
Cout<<“Maximum of two float: “<<m<<endl;
getch();
}
Output:
Maximum of two integers: 50
Maximum of two floats:4.8
11.
12. Class templates are generally
used for data storage classes.
Stacks and linked lists are
examples of data storage
classes.
The examples of these
classes(data storage classes)
that we present could store data
of only a single basic type.
14. class Stack
{
› private:
int st[MAX]; //array of int
int top; //index number of top of
stack
› public:
Stack(); //constructor
void push(int var); //takes int as argument
int pop(); //returns int value
};
15. If we wanted to store data of
type long in a stack, we would
need to define a completely
new class.
16. class LongStack
{
› private:
long st[MAX]; //array of longs
long top; //index number of top of stack
› public:
LongStack(); //constructor
void push(long var); //takes long as argument
long pop(); //returns long value
};
18. The basic syntax for declaring
template class:
template <class Type>
class Cont
{
› ……
};
19. Example of class template
that handle variables of all /
different data types is shown
20. // tempstak.cpp
// implements stack class as a template
#include <iostream.h>
using namespace std;
const int MAX = 100; //size of array
template <class Type>
class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
public:
Stack() //constructor
{ top = -1; }
void push(Type var) //put number on stack
{ st[++top] = var; }
Type pop() //take number off stack
{ return st[top--]; }
24. Class templates differ from function
templates in the way they are
instantiated.
To create an actual function from a
function template, you call it using
arguments of a specific type.
25.
26. Old C language signaled many errors for
returning a particular value from the
functions.
Setjump() and Longjump() functions
were used for handling errors there (very
difficult to use).
This approach is not appropriate in C++.
It handles errors in a different way using
“Exceptions”.
27. The exception syntax consists of:
First of all, there should be an exception
class.
Throw Exception (To handle an error)
Try Block (A code that uses objects)
Catch Block (Catches exception
through member function)
28.
29. // not a working program
class AClass //a class
{
public:
class AnError //exception class
{
};
void Func() //a member function
{
if( /* error condition */ )
throw AnError(); //throw exception
}
};
int main() //application
{
try //try block
{
AClass obj1; //interact with AClass objects
obj1.Func(); //may cause error
}
catch(AClass::AnError) //exception handler
{ //(catch block)
//tell user about error, etc.
}
return 0;
}
30. // demonstrates exceptions
#include <iostream>
using namespace std;
const int MAX = 3; //stack holds 3 integers
class Stack
{
private:
int st[MAX]; //array of integers
int top; //index of top of stack
public:
class Range //exception class for Stack
{ //note: empty class body
};
34. First of all, exception class should be
specified as follows:
Class Range
{ empty class body};
35. Exception will occur in previous program
if application tries to pop a value when
stack is empty and push a value when
stack is full.
Throw Range() will perform this task here.
36. Statements that manipulate stack (class
name) objects, are enclosed in try block.
try
{
//code that operates on objects that
might cause exception
}
37. Code that handles exceptions is
enclosed in braces, preceded by catch
keyword.
catch(stack::Range)
{
//code that handles exception
}
38. Normal execution outside try block.
Control enters the try block.
An error occurs in try block (in main
function).
Member function throws an exception.
Control transfers to exception handler.
39. // demonstrates two exception handlers
#include <iostream>
using namespace std;
const int MAX = 3; //stack holds 3 integers
class Stack
{
private:
int st[MAX]; //stack: array of integers
int top; //index of top of stack
public:
class Full { }; //exception class
class Empty { }; //exception class
Stack() //constructor
{ top = -1; }
void push(int var) //put number on stack
{
if(top >= MAX-1) //if stack full,
throw Full(); //throw Full exception
st[++top] = var;
}
49. The exception statements need not be in
the try block directly.
It can be in a function that is called by a
statement in try block.
However, try part must be included
before catch part.
50. The class libraries sold by any developer
may contain errors. They can cause
problems. These problems can be
resolved using Exceptions.
51. Do not use exceptions for simple
purposes that can be solved using loops
and other structures. Use exceptions for
handling difficult tasks only because they
effect the program size.
52. In exception mechanism, destructors are
called automatically. So the space
reserved by them is swiped clean easily.
Code in every exception will be reset.
53. When you catch an
exception, sometimes you terminate
your application. Exception mechanism
cleans up chores before terminating. In
short, it executes destructors. If there is no
exception handler, the program is
terminated by operating system.
Editor's Notes
The keyword 'class' above simply means that the identifier Type will stand for a datatype. NB: a_type is not a keyword; it is an identifier that during the execution of the program will represent a single datatype. For example, you could, when defining variables in the class, use the following line:Typea_var;and when the programmer defines which datatype 'a_type' is to be when the program instantiates a particular instance of a_class, a_var will be of that type.When defining a function as a member of a templated class, it is necessary to define it as a templated function:template<class Type> void a_class<Type>::a_function(){...} When declaring an instance of a templated class, the syntax is as follows:a_class<int> an_example_class; An instantiated object of a templated class is called a specialization; the term specialization is useful to remember because it reminds us that the original class is a generic class, whereas a specific instantiation of a class is specialized for a single datatype (although it is possible to template multiple types).Usually when writing code it is easiest to precede from concrete to abstract; thereforePrivate:Type variable;Public:{Type funct();}