C++ member function template
When was not necessary. we could have defined 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 functions template it takes the following general form
< class T >
classname< t >::functionname(arglist)
{
}
|
The vector class template and its member functions are redefined as follows
< class T >
class vector
{
T* v;
size;
:
vector(int m);
vector(T* a);
T operator*(vector & y);
};
template< class T >
< t >:: Vector( m);
{
v=new T[size=m];
( i=0;i < size;i++)
v[i]=0;
}
template< class T >
< T >::vector< T* a)
{
( i=0;i < size;i++)
v[i]=a[i];
}
template< class T >
T vector< T >:: operator*(vector & y)
{
T sum=0;
( i=0;i < size;i++)
{
T sum=0;
( i=0;i < size;i++)
sum+=this->v[i]*y..v[i];
sum;
}
}
|
OVERLOADING OF TEMPLATE FUNCTIONS
A template function may be overloaded wither by template function or ordinary functions of its name.
In such types cases the overloading resolution is accomplished as follows
1. call an general function that has an exact match.
2. call a template function that could be create with an exactly match.
3. Try the normal overloading resolution to ordinary functions and call the one that matches.
An Error is generated when no match is found. Note: that no automatic conversions are applied to arguments on the template functions
in the below example shows how a template function is overloaded with an explicit function.
TEMPLATE FUNCTION WITH EXPLICIT FUNCTION
<iostream>
<string>
using namespace std;
template<class T>
display(T x)
{
cout<<"Template display:" << x << "\n";
}
display(int x) // overloads the
{
cout << "Explicit display:" << x << "\n";
}
main()
{
display(100);
display(12.34);
display('c');
}
|
The output
Explicit display:100
Template display:12.34
template display:C
|
Note: The call display(100) invokes the ordinary version of display() and not the template version.
NON TYPE TEMPLATE ARGUMENTS
We have seen in previous that a template can have multiple arguments. It’s also possible to use non type
arguments. That is in addition to the type argument T, we can also use other arguments or parameters such as strings, function names, constant expressions and built in types. consider the following example
< T, size >
array
{
T a[size];
};
|
This template supplies the size of the array as an argument in above program. This implies that the size of the array is known to the compiler at the compiler time itself. The arguments or paramteres must be specified whenever a template class is created
example
array< int,10 > a1;
Array< float,5 > a2;
array< char,20 > a3;
The size is given as an argument to the template class
|