The following code example shows the class template Array and its instantiations and the function template square and its instantiations.
1 template<class C> void square(C num, C *result) 2 { 3 *result = num * num; 4 } 5 6 template<class T> class Array 7 { 8 public: 9 int getlength(void) 10 { 11 return length; 12 } 13 14 T & operator[](int i) 15 { 16 return array[i]; 17 } 18 19 Array(int l) 20 { 21 length = l; 22 array = new T[length]; 23 } 24 25 ~Array(void) 26 { 27 delete [] array; 28 } 29 30 private: 31 int length; 32 T *array; 33 }; 34 35 int main(void) 36 { 37 int i, j = 3; 38 square(j, &i); 39 40 double d, e = 4.1; 41 square(e, &d); 42 43 Array<int> iarray(5); 44 for (i = 0; i < iarray.getlength(); ++i) 45 { 46 iarray[i] = i; 47 } 48 49 Array<double> darray(5); 50 for (i = 0; i < darray.getlength(); ++i) 51 { 52 darray[i] = i * 2.1; 53 } 54 55 return 0; 56 } |
In the example:
Array is a class template
square is a function template
Array<int> is a class template instantiation (template class)
Array<int>::getlength is a member function of a template class
square(int, int*) and square(double, double*) are function template instantiations (template functions)