C++ Templates: The Complete Guide
| Ru-Brd |
| This part introduces the general concept and language features of C++ templates. It starts with a discussion of the general goals and concepts by showing examples of function templates and class templates. It continues with some additional fundamental template techniques such as nontype template parameters, the keyword typename , and member templates. It ends with some general hints regarding the use and application of templates in practice. This introduction to templates is also partially used in Nicolai M. Josuttis's book Object-Oriented Programming in C++ , published by John Wiley and Sons Ltd, ISBN 0-470-84399-3. This book teaches all language features of C++ and the C++ standard library and explains their practical usage in a step-by-step tutorial. Why Templates?
C++ requires us to declare variables , functions, and most other kinds of entities using specific types. However, a lot of code looks the same for different types. Especially if you implement algorithms, such as quicksort , or if you implement the behavior of data structures, such as a linked list or a binary tree for different types, the code looks the same despite the type used. If your programming language doesn't support a special language feature for this, you only have bad alternatives:
If you come from C, Java, or similar languages, you probably have done some or all of this before. However, each of these approaches has its drawbacks:
Templates are a solution to this problem without these drawbacks. They are functions or classes that are written for one or more types not yet specified. When you use a template, you pass the types as arguments, explicitly or implicitly. Because templates are language features, you have full support of type checking and scope. In today's programs, templates are used a lot. For example, inside the C++ standard library almost all code is template code. The library provides sort algorithms to sort objects and values of a specified type, data structures (so-called container classes ) to manage elements of a specified type, strings for which the type of a character is parameterized, and so on. However, this is only the beginning. Templates also allow us to parameterize behavior, to optimize code, and to parameterize information. This is covered in later chapters. Let's first start with some simple templates. |
| Ru-Brd |