Function templates
Function templates are also allowed. These specify a family of functions, which are defined by the
same rules as overloading of arguments. Thus:
int a, b;
float c,d;
template T max(T a, T b){ return a>b?a:b; };
int v1 = max(a,b);
float f1 = max(c,d);
Again the types must match properly. Each of the types in the template argument list must be used
in at least one of the arguments of the function, to allow resolution at call.
#include<iostream.h>
template class Array{
private:
T * arr;
int sz;
public:
Array(int size);
Array(const Array& arr2);
virtual ~Array();
Array & operator = (const Array& arr2);
T& operator [] (int j);
};
template Array ::Array(int size) {
sz = size;
arr = new T[size];
}
template Array ::~Array() {
delete [] arr;
}
template T& Array ::operator [] (int j) {
return arr[j];
}
void main() {
Array darr(20);
for(int i=0;i<20;i++) darr[i]=i*3.4;
cout<
Plain text to compile and run.
Next note in series
Back to index