Breaking News

Function Templates In C++

We can also define function templates that could be used to create a family of functions with different arguments types. The general format template is:
 
template< class T>
return-type functionname (arguments of type T)
{
//……..
//body of function
//with type T
//where ever appropriate
//………
}
 
Suppose you want to write a function that returns the minimum of two numbers. Ordinarily this function would be written for a particular data types.
 
For Example
 
int min(int a,int b)
{
return(a<b)? a:b;
}
 
The following program shows how to write the min() functions a template, so that it will work with any standard type. we have invoked this function from main() for different data types.
 
template
T min( T a, T b)
{
return( a> b ) ? : b ;
}
 
void main()
{
int i =10,int j =20;
cout << endl << min(i, j)
char ch = ‘A’ , dh = ‘Z’;
 
double d=1.1, e=1.11;
cout<<endl<<min(d,e);
}
 
Here’s the output of the program:
 
10
-6.28
A
1.1
 
Function Template with multiple Parameters
 
We can also write a function template that takes different types of arguments during one call.
 
template < class T1, class T2, ….>
return-type function-name ( arguments of types T1, T2, ….)
{
………………
………………
………………
}
 
Example :
 
 
Out put of the program :
 
 
Function Template Overloading
 
A template function may be overloaded either by templates or ordinary functions of its name.
 
In such cases, the overloading resolution is accomplished as follows:
 
Call an ordinary function that has an exact match.
 
Call a template function that could be created with an exact match.
 
Try normal overloading resolution to ordinary functions and call the one that matches.
 
Member Function Templates
 
When we created a class template for vector, all the member functions were defined as inline which was not necessary. We could have defined them outside the class as well.
 
But remember that the member functions of the template classes themselves are parameterized by the type argument (to their template classes) and therefore these functions must be defined by the function templates.
 
It takes the following general form:
 
template < class T>
return-type classname :: functionname (arglist)
 
{
//……………….
//function body
//………………..
}
 
Example :
 
//class template………………..
template< class T >
class vector
 
{
T*,v;
int size;
public :
vector (int m );
vector (T*,a);
T operator* (vector & y);
};
//member function template………….
template class T
vector : : vector(int m);
 
{
v = new T [size m];
for(int i = 0 ; i < size ; i++)
v[i]=0;
}
template <class T>
vectot : : vector (T*,a)
 
{
for(int i = 0 ; i < size ; i++)
v [i] = a[i];
}
template <class T>
T vector < T > :: operator*(vector & y)
 
{
T sum = 0;
for(int i = 0; i < size; i++)
sum += this -> v[i] * y.v[i];
return sum;
}

Check Also

Virtual Functions In C++

  Virtual function is a member function of a base class and redefined by a …