Team LiB
Previous Section Next Section

Chapter 16. Templates and Generic Programming

 

Contents

 

Section 16.1 Defining a Template

 

Section 16.2 Template Argument Deduction

 

Section 16.3 Overloading and Templates

 

Section 16.4 Variadic Templates

 

Section 16.5 Template Specializations

 

Chapter Summary

 

Defined Terms

 

Both object-oriented programming (OOP) and generic programming deal with types that are not known at the time the program is written. The distinction between the two is that OOP deals with types that are not known until run time, whereas in generic programming the types become known during compilation.

 

The containers, iterators, and algorithms described in Part II are all examples of generic programming. When we write a generic program, we write the code in a way that is independent of any particular type. When we use a generic program, we supply the type(s) or value(s) on which that instance of the program will operate.

 

For example, the library provides a single, generic definition of each container, such as vector. We can use that generic definition to define many different types of vectors, each of which differs from the others as to the type of elements the vector contains.

 

Templates are the foundation of generic programming. We can use and have used templates without understanding how they are defined. In this chapter we’ll see how to define our own templates.

 

Templates are the foundation for generic programming in C++. A template is a blueprint or formula for creating classes or functions. When we use a generic type, such as vector, or a generic function, such as find, we supply the information needed to transform that blueprint into a specific class or function. That transformation happens during compilation. In Chapter 3 and Part II we learned how to use templates. In this chapter we’ll learn how to define them.

 
Team LiB
Previous Section Next Section