< previous page page_420 next page >

Page 420
The Standard Template Library
A new development in C++ is the adoption of the Standard Template Library (STL). All the major compiler vendors now offer the STL as part of their compiler. STL is a library of template-based container classes, including vectors, lists, queues, and stacks. The STL also includes a number of common algorithms, including sorting and searching.
The goal of the STL is to give you an alternative to reinventing the wheel for these common requirements. The STL is tested and debugged, offers high performance, and its free! Most important, the STL is reusable; when you understand how to use an STL container, you can use it in all your programs without reinventing it.
Summary
In this hour you learned how to create and use templates. Templates are a built-in facility of C++ used to create parameterized typestypes that change their behavior based on parameters passed in at creation. They are a way to reuse code safely and effectively.
The definition of the template determines the parameterized type. Each instance of the template is an actual object, which can be used like any other objectas a parameter to a function, as a return value, and so forth.
Q&A
Q Why use templates when macros will do?
A Templates are type-safe and built into the language.
Q What is the difference between the parameterized type of a template function and the parameters to a normal function?
A A regular function (non-template) takes parameters on which it may take action. A template function allows you to parameterize the type of a particular parameter to the function. That is, you can pass an ListOfType to a function, and then have the Type determined by the template instance.
Q When do you use templates and when do you use inheritance?
A Use templates when all the behavior or virtually all the behavior is unchanged, but the type of the item on which your class acts is different. If you find yourself copying a class and changing only the type of one or more of its members, it may be time to consider using a template.

 
< previous page page_420 next page >

If you like this book, buy it!