[   ^ to index...   |   <-- previous   ]

More on template arguments

Templates may have multiple arguments; frequently we specify policy in our template arguments for flexibility. Arguments may be types or simple values (the latter can include function pointers).

Multiple class arguments

Suppose we wanted to parameterize our sort. We could pass a function pointer to the sort method, but function pointers are hard to optimize and also rather opaque. We can factor the notion of comparison out into a Comparator:

template <class T, class Comparator> void sort(T *array, int length) { // ... some stuff, then: if (Comparator::less_than(array[i], array[j])) { // ... stuff ... } } template <class T> class DefaultComparator { static bool equals(T a, T b) { return a == b; } static bool less_than(T a, T b) { return a < b; } }; class Foo; Foo array[LENGTH]; // ... etc. sort<Foo, DefaultComparator<Foo>>(array, LENGTH);

Note that we now have the freedom to write a totally different Comparator for Foo, one that does not simply use its operator= and operator< methods.

Simple values

A common use for passing simple values is to define a "default" value for some operation--for example, the initial size of a dynamically sized vector:

template <class T, int init_length> class Vector { public: Vector() { items = new T[init_length] } // ... etc. private: T * items; }; Vector<int, 5> v;

Last modified: Mon Jul 31 22:13:35 PDT 2000