Skip to main content
Templates
Templates
 Templates allows us to create a single function or
class for a group of similar function or class in
generic manner.
 Templates can be categorized into two categories:
Function Template:-template declared for function is
called function template
Class Template:- template declared for class is called
class template
Need of template
#include<iostream.h>
int min(int a,int b)
{
return (a<b?a:b);
}
float min(float a,float b)
{
return(a<b?a:b);
}
Void main()
{
int x,y;
float p,q;
Cout<<“enter values”;
Cin>>x>>y;
Cout<<“min of integers”<<min(x,y);
Cout<<“floati no”;
Cin>>p>>q;
Cout<<“min of floating values”<<min(p,q);
getch();
}
Syntax
template<class T>
T function_nane(T par1,T par2)
{
……….//template function body
}
Example
#include<iostream.h>
#include<conio.h>
template<class T>
T min(T a, T b)
{
Return(a<b?a:b);
}
Void main()
{
int x,y;
float p,q;
Cout<<“enter integer value”;
Cin>>x>>y;
Cout<<“enter float value”;
Cin>>p>>q;
Cout<<“min of integer”<<min(x,y)<<endl;
Cout<<“min of floating value”<<min(p,q);
}
Function Template
• They allow to create generic functions
• They admit any data type as parameters
• They return a value without having to overload the
function with all the possible data types.
• The syntax to declare the function template is as
follows:
template <class identifier> function_declaration;
Class Template
A class can have members based on generic types
means their data type is not defined at the time of
creation of the class and whose members use these
generic types.
Syntax:
template <class T>
Class class_name
{
//class defination
};
Example
#include<iostream.h>
template <class T>
Class mix
{
T a,b;
Public:
mix(T x,Ty)
{
a=x;
b=y;
}
T max()
{
return (a>b?a:b);
};
void main
{
Mix<int> obj(10,20);
Cout<<“max value is”<<obj.max();
}