The C++ Function templates are the functions that can handle a different data types
without any separate code for all of the datatypes.
A D V E R T I S E M E N T
For the similar operation on the
several kinds of the data types, the programmer may need not write the different
versions by function overloading. C++ template based function is enough, it will take care
of all data types.
Let us cosider a small example for the Add function. If requirement is to use the Add
function to both types that is an integer and float type, then the two functions needs
to be created for each data type.
int Add(int a,int b)
{
return a+b;
}
// function Without C++ template
float Add(float a, float b)
{
return a+b;
}
// function Without C++ template
If the data types are more than two then it is difficult to be handled,
Because those many number of functions are to be added.
If we make use of the c++ function template, whole process will be reduced to
the single c++ function template. Here is the code fragment for the Add function.
template <class T>
T Add(T a, T b)
//C++ function template sample
{
return a+b;
}
The Class Templates
A C++ Class Templates are been used where we have the multiple copies of the code for
the different data types having the same logic. If the set of functions or the classes
have a same functionality for the different data types, they will become the good
candidates being written as the Templates.
A C++ class template declaration must starts with the keyword "template". The parameter
must be included inside the angular brackets. Parameter inside a angular brackets,
can either be the keyword class or the typename. This is then followed by a class body
declaration with a member data and the member functions. Following code is the
declaration for the sample Queue class.
//Sample code snippet for C++ Class Template
template <typename T>
class MyQueue
{
std::vector data;
public:
void Add(T const &d);
void Remove();
void Print();
};