Chapter 10: Templates

A function template is a framework for a function that can adapt itself to the data types of the arguments passed to it. Function templates were added to the C++ language to relieve the programmer of the burden of having to write multiple versions of the same function just to carry out the same operation on different data types. The compiler generates instances of the function when the function is called. A function template must have at least one argument, and that argument must be used in the function.

A class template is a generic framework that forms the basis for creating specific classes. One of the major goals of class templates is to eliminate the needless duplication of effort that would be required if separate versions of the same class had to be written and maintained. The generated classes differ only in those places where the template parameters appear in the template source code. Function and class templates are ordinarily placed in headers that are included by programs that call the functions or create class objects.

We demonstrated a function template called indexOf that searches a table of any nonpointer data type. We explained how arguments are matched in function calls to arguments in function declarations, and we also showed how to create specific template functions when needed.

We presented an Array class template that could be useful in a wide range of applications. The Array template can hold a variety of data types, and performs range checking on subscripts, exception handling, and dynamic memory allocation. We showed how to use the Array template in the Springboard Diving Competition program. We also presented a fixed-string class template called FTString and a Dictionary class template that compared keys to their associated values. These class templates were used to show how class templates relieve programmers of the burden of having to write and maintain multiple versions of nearly identical classes.

When distributing software that uses templates, it is important to realize that class users need to have copies of all of your template source code. Unfortunately, this presents a temptation for users to tinker with the code, possibly introducing errors.