You saw in Chapter 6 that you could define a function template that would automatically generate functions varying in the type of arguments accepted, or in the type of values returned. C++ has a similar mechanism for classes. A class template is not, in itself, a class, but a sort of “recipe” for a class that will be used by the compiler to generate the code for a class. As Figure 8-5 shows, it’s like a function template — you determine the class that you want generated by specifying your choice of type for the parameter (T, in this case) that appears between the angled brackets in the template. This generates a particular class that is referred to as an instance of the template. Creating a class from a template is described as instantiating the template.

An appropriate class definition is generated when you instantiate an instance of a template class with a particular type parameter, so you can generate any number of different classes from one class template. You’ll get a good idea of how this works in practice by looking at an example.

Defining a Class Template

I’ll choose a simple example to illustrate how you define and use a class template, and I won’t complicate things by worrying too much about possible errors that can arise if it’s misused. Suppose you want to define classes that can store a number of data samples of some kind, and each class ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.