Class Templates

Steven J. Zeil

Old Dominion University, Dept. of Computer Science

Table of Contents

1. Class Templates
2. Developing and Using Class Templates
2.1. Templates as a Pattern for Data
2.2. Instantiating Class Templates
2.3. Templates with Function Members
2.4. Tips for Implementing Templates
3. Example: Matrix
3.1. Start with a working class...
3.2. Combine into .h File
3.3. Add Template Parameters
3.4. Rewrite Class Names
3.5. Check Related Classes
4. Second Example: the pair class
4.1. Thinking in Terms of Tuples
4.2. The pair Template
4.3. Applications of pair<...>

Just as function templates allow us to write general patterns for functions, from which the compiler then generates multiple instances, so class templates allow us to write general patterns for classes.

Class templates are especially useful for containers, data structures that serve mainly as collections of other, smaller data types. In our spell checker, for example, we have used two different kinds of sets and two different kinds of ordered sequence. The code for the two sets was essentially the same -- only the data types of the contained data varied. The same is true if we compare the code for the two kinds of sequences.

Now, we certainly can get these different versions of the same container class by copying a file and editing it. But, as you've seen in the assignment at the beginning of the section, this approach can be tedious and error-prone. It also creates project management nightmares when a bug is fixed in one copy of an often-replicated container, and we must then find and fix all the copies.


In the Forum:

(no threads at this time)