You can use templates in a nested manner. This is particularly useful when defining generic functions over generic data structures, as in the standard C++ library. For example, a template sort function may be declared over a template array class:
template <class Elem> void sort(Array<Elem>); |
and defined as:
template <class Elem> void sort(Array<Elem> store) {int num_elems = store.GetSize(); for (int i = 0; i < num_elems-1; i++) for (int j = i+1; j < num_elems; j++) if (store[j-1] > store[j]) {Elem temp = store[j]; store[j] = store[j-1]; store[j-1] = temp;}} |
The preceding example defines a sort function over the predeclared Array class template objects. The next example shows the actual use of the sort function.
Array<int> int_array(100); // construct an array of ints sort(int_array); // sort it |