Overloading Function Templates
Function templates and overloading are intimately related. The function-template specializations generated from a function template all have the same name, so the compiler uses overloading resolution to invoke the proper function.
A function template may be overloaded in several ways. We can provide other function templates that specify the same function name but different function parameters. For example, function template printArray of Fig. 14.1 could be overloaded with another printArray function template with additional parameters lowSubscript and highSubscript to specify the portion of the array to output (see Exercise 14.4).
A function template also can be overloaded by providing nontemplate functions with the same function name but different function arguments. For example, function template printArray of Fig. 14.1 could be overloaded with a nontemplate version that specifically prints an array of character strings in neat, tabular format (see Exercise 14.5).
The compiler performs a matching process to determine what function to call when a function is invoked. First, the compiler finds all function templates that match the function named in the function call and creates specializations based on the arguments in the function call. Then, the compiler finds all the ordinary functions that match the function named in the function call. If one of the ordinary functions or function-template specializations is the best match for the function call, that ordinary function or specialization is used. If an ordinary function and a specialization are equally good matches for the function call, then the ordinary function is used. Otherwise, if there are multiple matches for the function call, the compiler considers the call to be ambiguous and the compiler generates an error message.
Common Programming Error 14.3
If no matching function definition can be found for a particular function call, or if there are multiple matches, the compiler generates an error. |