Templates
Need for Templates
Void sum(int x,int y)
{
int z;
z=x+y;
cout<<z;
}
Templates
Example
Function Template
template <class T>
return_type fname(argu of type T)
{
}
Example
template <class T>
void sum(T x, T y)
{
T z;
z=x+y;
cout<<z;
}
int main()
{
sum(5,10);
sum(6.5,7.5);
return 0;
}
Then
T sum(T x, T y)
Parameterized classes & functions
Function Template with multiple Parameters
template <class T1,class T2>
Void display(T1 x, T2 y)
{
cout<<x;
cout<<y;
}
int main()
{
display(8.25,’m’);
display(789,65.43);
return 0;
}
Class Template
Template<class T>
Class class_name
{
//With type where //appropriate
}
Template <class T>
Class sample
{
T x;
T y;
Public:
getdata(T a, T b)
{
x=a;
y=b;
}
display()
{
cout<<x;
cout<<y;
}
Void Main()
{
Sample<int> obj;
obj.getdata(4,6);
obj.display();
Sample <float> obj1;
Obj1.getdata(3.5,6.5);
Obj1.display();
}
Member function Template�We can define a member function outside the class, we have to declare the template before every member function.
Template <class T>
class_name<T>::fun_name(argu)
{
}
Template <class T>
void sample<T>::getdata(T a,T b)
{
x=a;
y=b;
}
Overloading of Template function
1. call an ordinary function that has an exact match
2. call a template function that could be created with an exact match.
3. An error is generated if no match is found.
Example
Template<class T>
Void display(T x)
{
cout<<“template display”
}
Void display(int x)
{
cout<<“explicit display”;
}
Void Main()
{
display(100);
display(3.4);
display(‘C’);
}
Non-type template arguments
Example
template<class T,int size>
class array
{
public:
T a[size];
void getdata()
{
cout<<"enter elements";
for(int i=0;i<size;i++)
{
cin>>a[i];
}
}
void display()
{
cout<<"elements are:";
for(int i=0;i<size;i++)
{
cout<<a[i];
}
}};
int main()
{
array<int,10> a1;
// array of 10 integers
array<float,5>a2;
// array of 5 floats
array<char,20>a3;
// string of size 20
a1.getdata();
a1.display();
return 0;
}
Write a function template for finding the maximum value in array.
Template<class T>
Void Max(t a[],int n)
{
int i;
T max=0;
for(i=0;i<n-1;i++)
{
If(a[i]>max)
{
max=a[i];
}
}
cout<<max;
}
Void main()
{
int x[5]={1,55,33,2,4};
Max(x,5);
}