Template Programs
Template Programs
1
array a1;
array a2;
a1.display();
a2.display();
a1=x;
a2=y;
a1.display();
a2.display();
int r=a1+a2;
cout<<"r="<<r<<endl;
return(0);
}
/* If we want to define an array that can store an array of float values, we can do this by
simply replacing the appropriate int declarations with float in array class. We have to
redefine the entire class all over again. */
/* The above problem i.e. redefinition of class can be avoided by defining a class with the
data type as parameter and then use this class to create an array of any data type. The
template mechanism enables us to achieve this goal.*/
2
int main()
{
int x[size]={2,4,6};
float y[size]={1.5,3.4,5.2};
array <int> a1;
array <float> a2;
a1.display();
cout<<"\n";
a2.display();
cout<<"\n";
a1=x;
a2=y;
a1.display();
cout<<"\n";
a2.display();
cout<<"\n";
return(0);
}
22. Class Template with multiple parameters
template<class T1,class T2>
class sample
{
T1 a;
T2 b;
public:
sample(T1 x, T2 y) { a=x; b=y; }
void display(void) { cout<<"a="<<a<<"b="<<b; }
};
int main()
{
sample <float,int> s1(1.23,123);
sample <int,char> s2(10,'a');
s1.display();
cout<<"\n";
s2.display();
cout<<"\n";
return(0);
}
23.Function Template
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
template<class T>
void swap(T &x,T &y)
{
T temp=x;
3
x=y;
y=temp;
}
void fun(int m,int n,float x,float y)
{
cout<<"m and n before swap"<<m<<" "<<n<<"\n";
swap(m,n);
cout<<"m and n after swap"<<m<<" "<<n<<"\n";
cout<<"x and y before swap"<<x<<" "<<y<<"\n";
swap(x,y);
cout<<"x and y after swap"<<x<<" "<<y<<"\n";
}
int main()
{
clrscr();
fun(10,20,2.5,3.4);
return(0);
}
24. Function Templates with multiple parameters
template<class T1,class T2>
void display(T1 x,T2 y) { cout<<"x ="<<x<<"y= "<<y<<"\n"; }
int main()
{
clrscr();
display(20,2.5);
display(20,"abc");
return(0);
}
4
p[i]=0;
}
}
template<class T>
array <T> ::array(T *a)
{
p=new T[size];
for(int i=0;i<size;i++)
p[i]=a[i];
}
template <class T>
void array <T>::display(void)
{
for(int i=0;i<size;i++)
cout<<"\t"<<p[i];
}
int main()
{
int x[size]={2,4,6};
float y[size]={1,3,5};
clrscr();
array <int> a1;
array <float> a2;
a1.display();
cout<<"\n";
a2.display();
cout<<"\n";
a1=x;
a2=y;
a1.display();
cout<<"\n";
a2.display();
return(0);
}
26. Non –Type Templates
5
{
cout<<"Constructor Called \n";
for(int i=0;i<size;i++)
{
cout<<"Enter "<<i<<"Value"; cin>>a[i];
}
}
template <class T,int size>
void array <T,size>::display(void)
{
for(int i=0;i<size;i++)
cout<<"\t"<<a[i];
}
int main()
{
clrscr();
array <int,5> a1; // array of 5 integers
a1.display();
cout<<"\n\n";
array <float,5> a2; // array of 5 floats.
a2.display();
cout<<"\n\n";
array<char,10> a3;
a3.display();
cout<<"\n\n";
return(0);
}
/* In addition to the type argument T, we can also use other arguments such as strings,
function names, constant expressions and built-in types. Size parameter specify the size
of array and is known to compiler at the compile time it self. */