The C++ Template Library - dummies

By Stephen R. Davis

The standard C++ library provides a complete set of math, time, input/output, and DOS operations, to name just a few. Many of the early programs that you learn as a beginner use the so-called character string functions defined in the include file strings.

The argument types for many of these functions are fixed. For example, both arguments to strcpy(char*, char*) must be a pointer to a null-terminated character string — nothing else makes sense.

There are functions that are applicable to multiple types. Consider the example of the lowly maximum() function, which returns the maximum of two arguments. All of the following variations make sense:

int maximum(int n1, int n2); // return max of two integers
unsigned maximum (unsigned u1, unsigned u2);
double   maximum (double d1, double d2);
char     maximum (char c1, char c2);

Here, you would like to implement maximum() for all four cases.

Of course, you could overload maximum() with all the possible versions:

double maximum(double d1, double d2)
    return (d1 > d2) ? d1:d2;
int maximum(int n1, int n2)
    return (n1 > n2) ? n1:n2;
char maximum(char c1, char c2)
    return (c1 > c2) ? c1:c2;
// ...repeat for all other numeric types...

This approach works. Now C++ selects the best match, maximum(int, int), for a reference such as maximum(1, 2). However, creating the same function for each type of variable is a gross waste of time.

The source code for all the maximum(T, T) functions follows the same pattern, where T is one of the numeric types. It would be so convenient if you could write the function once and let C++ supply the type T as needed when the function is used. In fact, C++ lets you do exactly this. They are called template definitions.