Template class help us to use generic
classes and functions. Template allows a function or class to work on many
different data types without being rewritten for each one. Instead of writing
multiple overloaded function for the same purpose but with different data types
we can use template class and do the same with a single function.
Function template
Function template : Function
templates are special kind of functions that can operate with generic data
types and this can be achieved using template parameters. A template parameter
is a special kind of parameter that can be used to pass a type as argument as
we do with regular function parameters. These function templates can use these
parameters of different types to perform necessary routines.
The
format for declaring function templates with type parameters is:
template
<class list of identifiers>
function_declaration(
template type identifier)
Example
: Displaying different data types using Function Template
#include
<iostream.h>
template<class t1,class t2>
void fun(t1 a,t2 b)
{
cout<<a<<”\t”<<b;
}
int main()
{
int x=4;
float y=5.9;
char z='S';
fun(x,y); // <int,float>
fun(y,z); // <float,char>
fun(z,x); // <char,int>
return 0;
}
Example : Maximum of the two elements
#include
<iostream.h>
template <class T>
T max(T a, T b)
{
return a > b ? a : b ;
}
void main()
{
int a,b;
float x,y;
char ch,ch1;
cout<<"\n\tEnter
two Integer Nos. : ";
cin>>a>>b;
cout<<"\n\tEnter two Real
Nos. : ";
cin>>x>>y;
cout<<"\n\tEnter two
Characters : ";
cin>>ch>>ch1;
cout<<"\n\n\tMaximum
of "<<a<<" and "<<b<<"
is = "<<max(a,b);
cout<<"\n\n\tMaximum
of "<<x<<" and "<<y<<"
is = "<<max(x,y);
cout<<"\n\n\tMaximum
of "<<ch<<" and "<<ch1<<"
is = "<<max(ch,ch1);
}
Example : Swapping two elements
#include
<iostream.h>
template <class T>
void swap(T
&a, T &b)
{
T c;
c=a;
a=b;
b=c;
}
void main()
{
int a,b;
float x,y;
char ch,ch1,*S,*S1;
cout<<"\n\tEnter
two Integer Nos. : ";
cin>>a>>b;
cout<<"\n\tEnter two Real
Nos. : ";
cin>>x>>y;
cout<<"\n\tEnter two
Characters : ";
cin>>ch>>ch1;
cout<<"\n\tEnter
two Strin : ";
cin>>S>>S1;
cout<<"\n\n\tOrginal
Input : "<<a<<","<<b;
swap(a,b);
cout<<"
AfterSwap : "<<a<<","<<b;
cout<<"\n\n\tOrginal
Input : "<<x<<","<<y;
swap(x,y);
cout<<"
AfterSwap : "<<x<<","<<y;
cout<<"\n\n\tOrginal
Input : "<<ch<<","<<ch1;
swap(ch,ch1);
cout<<"
AfterSwap : "<<ch<<","<<ch1;
cout<<"\n\n\tOrginal
Input : "<<S<<","<<S1;
swap(S,S1);
cout<<"
AfterSwap : "<<S<<","<<S1;
}
No comments:
Post a Comment