Chapter 11. Writing Generic Code with Templates
C++ provides language support not only for object-oriented programming, but also for generic programming. As discussed in Chapter 5, 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. Unfortunately, many programmers consider templates to be the most difficult part of C++ and, for that reason, tend to avoid them. However, even if you never write your own templates, you need to understand their syntax and capabilities in order to use the C++ standard library.
This chapter provides the code details for fulfilling the design principle of generality discussed in Chapter 5 and prepares you to understand the standard template library, which is discussed further in Chapters 21 to 23. The chapter is divided into two halves. The first half presents the most commonly used template features, including:
How to write template classes
How the compiler processes templates
How to organize template source code
How to use nontype 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
The second half of the chapter delves into some of the more ...
Get Professional C++ 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.