- Expert C++
- Vardan Grigoryan Shunguang Wu
- 366字
- 2021-06-24 16:34:05
Motivation
So far,when we have defined a function or a class, we have had to provide input, output, and intermediate parameters. For example, let's say we have a function to performs the addition of two int type integers. How do we extend this so that it handles all the other basic data types, such as float, double, char, and so on? One way is to use function overloading by manually copying, pasting, and slightly modifying each function. Another way is to define a macro to do the addition operation. Both approaches have their own side effects.
Moreover, what happens if we fix a bug or add a new feature for one type, and this update needs to be done for all the other overloading functions and classes later? Instead of using this silly copy-paste-and-replacement method, do we have a better way of handling this kind of situation?
In fact, this is a generic problem that any computer language can face. Pioneered by the general-purpose functional programming Meta Language (ML) in 1973, ML permits writing common functions or types that differ only in the set of types that they operate on when used, thus reducing duplication. Later inspired by the parameterized modules provided in the chartered life underwriter (CLU) and the generics provided by Ada, C++ adopted the template concept, which allows functions and classes to operate with generic types. In other words, it allows a function or class to work on different data types without them needing to be rewritten.
Actually, from an abstract point of view, C++ functions or class templates (such as cookie cutters) serve as a pattern for creating other similar functions or classes. The basic idea behind this is to create a function or class template without having to specify the exact type(s) of some or all variables. Instead, we define a function or class template using placeholder types, called template type parameters. Once we have a function or class template, we can automatically generate functions or classes by using an algorithm that has been implemented in other compilers.
There are three kinds of templates in C++: function templates, class templates, and variadic templates. We'll take a look at these next.