Contents
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 vector
s, 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.