Chapter 19

Writing Generic Code with Templates


  • How to write template classes
  • How the compiler processes templates
  • How to organize template source code
  • How to use non-type template parameters
  • How to write templates of individual class methods
  • How to write customizations of your class templates for specific types
  • How to combine templates and inheritance
  • How to write function templates
  • How to make template functions friends of template classes
  • How to write template aliases

C++ provides language support not only for object-oriented programming, but also for generic programming. As discussed in Chapter 4, the goal of generic programming is to write reusable code. The fundamental tools for generic programming in C++ are templates. Although not strictly an object-oriented feature, templates can be combined with object-oriented programming for powerful results. Many programmers consider templates to be the most difficult part of C++ and, for that reason, tend to avoid them.

This chapter provides the code details for fulfilling the design principle of generality discussed in Chapter 4 and used during the discussion of the standard template library in Chapters 11 through 17.

The next chapter delves into some of the more advanced template features, including:

  • The three kinds of template parameters and their subtleties
  • Partial specialization
  • Function template deduction
  • How to exploit template recursion
  • Variadic templates
  • Metaprogramming


Get Professional C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.