Generic Functions in C++
Generic functions in C have the descriptive name of template functions. The definition of a template function has the general form template <template parameters>
—a function definition that may include the template parameters
A template parameter (there must be at least one) has one of the forms
The class form is used for type names. The typename form is used for passing a value to the template function. For example, it is sometimes convenient to pass an integer value for the size of an array in the template function.
A template can take another template, in practice often a template class that defines a user-defined generic type, as a parameter, but we do not consider that option here.
As an example of a template function, consider the following:
where Type is the parameter that specifies the type of data on which the function will operate. This template function can be instantiated for any type for which the operator > is defined. For example, if it were instantiated with int as the parameter, it would be
Although this process could be defined as a macro, a macro would have the disadvantage of not operating correctly if the parameters were expressions with side effects. For example, suppose the macro were defined as
This definition is generic in the sense that it works for any numeric type. However, it does not always work correctly if called with a parameter that has a side effect, such as
Whenever the value of x is greater than that of y, x will be incremented twice.
C template functions are instantiated implicitly either when the function is named in a call or when its address is taken with the & operator. For example, the example template function defined would be instantiated twice by the following code segment—once for int type parameters and once for char typeparameters: