Templates
are the mechanism that makes a possible to use one function or class to handle
many different data types. By using template, we can design a single class or
function that operates on data of many types, instead of having to create a
separate class or function or each type. When used with functions, they are
known as function templates whereas when used with classes they are called as
class templates.
Function
templates Generic function
#include<iostream.h>
template
<class T>
T
min (Ta,Tb)
{
return(a<b)?a:b;
}
void
main ()
{
int
i=10, j=20;
cout<<”Min
interger value=”<<min(i,j);
cout<<”Min
float value=”<<min(f1,f2);
getch();
}
Templates
provide a way to reuse the source code. Templates can increase code flexibility
without reducing type safety
Here
is the definition of minimum function
template
<class T>
T
min (Ta,Tb)
{
return(a<b)?a:b;
}
This
entire syntax is called function template. In a function template a data type
can be represented by a name( T in this case) that can stand for any type. Instead of T we can use any name like ‘type”, “mytype”
etc. T is known as template argument. Throughout the definition of function, wherever
a specific data type like int could ordinary be written, we substitute the
template argument “T”.
Class
template:
Class
templates are usually used for data storage (container) classes. Stacks and link
list are example container classes. Using class Templates, users can work for variable
of all types instead of a single basic type.
#define
MAX 10
Template
<class T>
class
stack
{
Task[MAX];
T
data;
int
top;
public:
stack(
)
{
top=-1
}
void
push(T data)
{
if(top==MAX-1)
{
cout<<
“stack is full\n”;
return;
}
else
{
top++;
stk[top]=data;
}
}
T
top( )
{
if
(top==-1)
{
cout<<
“stack is empty \n”;
return
NULL;
}
else
{
T
data=stk[top];
top--;
return
data;
}
}
};
void
main( )
{
stack<int>s1;
s1.push(10);
s1.push(15);
s1.push(20);
cout<<
“Popped element=” s1.pop( );
cout<<
“popped element” << s1.pop ( );
cout
<< “popped element” <<s1.pop( );
stack
<float> s2;
s2.puch(10.5)
s2.push(15.5)
s2.push(20.5);
cout<<
“ Pop element=”<<s2.pop();
cout
<< “pop element=”<<s2.pop( );
cout
<< “pop element=”<<s2.pop( );
getch(
);
}
Defining
a member function of a class template outside the class. The syntax is
Template<Class
T>
void
stack<T>:push(T data)
{
..
..
}
The
expression template <class T>must preceded not only the class definition,
but each externally defined member function. The name stack (T) (in this case)
is used to identify the class of which push ( ) is a member.