Tuesday 13 November 2012

Generic function and Class Template in c++

Generic function and Class Template
C++ templates can be used both for classes and for functions in C++.

Function Template
Function template is also known as generic function
The main advantage of function overloading is that you can use same name of function for performing similar tasks in different parts of a program.
If you want to accommodate more data types, you will require additional versions of function. This is the main disadvantage of function overloading.
However, C++ compilers have a facility called template which will help you create only one version of function. This version will accommodate different data types of C++. A function which works for all data types of C++ is called a generic function or a function template.
Syntax is:template <class type> type func_name(type arg1, ...);
type is any name of your choice, which is a placeholder name for a data type used by the function. The name X is replaced by actual data type when the compiler creates a specific version of the function.

Example
#include<iostream.h>
#include<conio.h>
template <class X> X big(X a, X b)
{
return ((a>b)?a:b);
}
void main()
{
cout<<”\n Bigger of two is: ”<<big(21,16)<<”\n”;
cout<<”\n Bigger of two is: ”<<big(13.44, 16.54)<<”\n”;
cout<<”\n Bigger of two is: ”<<big(‘E’, ‘L’)<<”\n”;
}


The output look like:
Bigger of two is: 21
Bigger of two is: 16.54
Bigger of two is: L



Generic Class or Class Template

Syntax


template <class X> class class-name
{


}



Example

#include<conio.h>
#include<iostream.h>
template <class X> class xyz
{
X pdata;
public:
xyz() { }
xyz(X n)
{
pdata=n;
}
void show()
{
cout<<pdata;
}
~xyz() { }
};
void main()
{
clrscr();
xyz<int> data1(20);
cout<<"\n data1=";
data1.show();
xyz<int> data2;
data2=data1;
cout<<"\ndata2= ";
data2.show();
xyz<float> data3(195.05);
cout<<"\ndata3 = ";
data3.show();
xyz<long> data4(356432L);
cout<<"\ndata4=";
data4.show();
getch();
}

Explanation
To make class generalize in terms of data type we can make class template
Here X is a place holder for data type.
Notice the way object is created data type for the place holder must be mentioned in angular brackets.
It is obvious that the size of object depends on data type for place holder.

No comments:

Post a Comment