Chapter 24. Templates

Thou cunning’st pattern of excelling nature.

—Shakespeare, Othello, Act V

What Is a Template?

Templates are a relatively new addition to C++. They allow you to write generic classes and functions that work for several different data types. The result is that you can write generic code once and then use it over and over again for many different uses. In fact, C++ comes with something called the Standard Template Library (STL), which makes extensive use of templates to provide powerful data-processing tools to the C++ user.

There are some problems with templates, however. Working out the implementation details was very difficult for the people on the C++ Standards Committee. There was a lot of hard fighting involving tanks, mortars, and heavy artillery (or the academic equivalent, which is a tartly worded memo). As a result, template implementation details were one of the last items in the C++ Standard to be agreed upon. Later in this chapter, we’ll discuss some of the implementation problems with templates.

Templates: The Hard Way

Suppose we want to define a function max to return the maximum of two items. Actually, we don’t want to define just one max function, but a family of functions: one to find the maximum of two ints, one for floats, one for chars, and so on.

We start by defining a parameterized macro to generate the code for the function. This is called the definition stage . The macro looks like this:

#define define_max(type) type max(type d1, ...

Get Practical C++ Programming, 2nd Edition 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.