Templates – Function templates, Class templates| OOP in C++


TEMPLATES


(a) C++ supports a mechanism known as template to implement the concept of generic programming.
(b) Templates allows us to generate a family of classes or a family of functions to handle different data types.
(c) Template classes and functions eliminate code duplication for different data types.
(d) We can use multiple parameters in both the class templates and function templates.
(e) A specific class created from a class template is called a template class and the process of creating a template class is known as instantiation.
(f) Like other functions, template function can be overloaded.
(g) Member functions of a class template must be defined as function templates using the parameters of class template.
The general format for class template
template<class T>
class classname
{
class member specification with T
};
Program to multiply and sum the elements of two arrays using template 
Example: 


const int size=4;
template <class T>
class vector
{
T *v;
public:
vector() //create and initialize an array with zero
{
v=new T[size];
for(int i=0; i<size; i++)
v[i]=0;
}
vector (T *a) //copy an array pointed by *a to v
{
for(int i=0; i<size; i++)
v[i]=a[i];
}
T operator *(vector &y)
{
T sum=0;
for(int i=0; i<size; i++)
sum=sum + this->v[i]+y.v[i];
return sum;
}};
int main()
{
float c1[4]={1.1, 2.2, 3.3, 4.4};
float c2[4]={5.5, 6.6, 7.7, 8.8};
vector <float> v1;
vector <float> v2;
v1=c1;
v2=c2;
float addition = v1*v2;
cout<<"\n sum="<<addition;
return 0;
}


Class Template with multiple Parameters

The following program demonstrates the multiple parameters( ITEM NAME and PRICE) passing using a class template. The program accepts data using constructor calling and displays data using show() function of class "item".
Example


const int size =15;
template <class T1, class T2> //two parameters
class item
{
T1 *arr;
T2 *price;
public:
item()
{
arr=new T1[size];
price=new T2;
}
item (T1 *s, T2 p)
{
arr=s;
*price=p;
}
void show(void)
{
cout<<"\n Item Name="<<"\n Price="<<price;
}
};
int main()
{
item <char, float> item1("soap", 45.25);
item <char, int> item2("Biscuit", 20);
item1.show();
item2.show();
}


Function Template
Function templates can be used to create a family of functions using different data types.
Syntax
template<class T>
return-type function_name(arguements of type T)
{
Body of function using type T
}


Bubble Sort Using Template Function


template <class T>
void bubble (T a[], int size)
{
for(int i=0; i<size-i; i++)
{
for(int j=0; j<size-1-i; j++)
{
if(a[j]>a[j+1])
{
swap(a[j], a[j+1]);}
}}}
template <class Y>
void swap(Y &c, Y &d)
{
Y temp=c;
c=d;
d=temp;
}
int main()
{
int arr1[5]={9, 7, 2, 5, 3};
float arr2[5]={7.7, 5.5, 3.3, 2.2};
swap(arr1, 5);
swap(arr2, 5);
cout<<"\n arr1:";
for(int i=0; i<5; i++)
cout<<arr[i]<<",";
cout<<"\n arr2:";
for(i=0; i<5; i++)
cout<<arr2[i]<<",";
}
Output:

Custom Search

%d bloggers like this: