1 2 3 4 5 6 7 8 9
|
template<typename T> int compare(T &a,T &b);
int compare(const char *a,const char *b);
void foo()
{
char ch_arr1[6]="world",ch_arr2[6]="hello";
compare(ch_arr1,ch_arr2);
}
|
A parameterized function can be overloaded as in our example - ie. it has the same name as a nonparameterized function. And when the function is invoked, the call can be resolved either to an instantiation of the function template or to the non-template function. Normal function overload resolution process is used to determine which function best matches the arguments on the call.
Step 1.
-------
Identify the set of candidate functions - the set of the functions that have the same name as the called function, and for which a declaration is visible at the point of the call.
The non-template function is an obvious addition to the candidate list. An instantiation of the function template (the template function can be instantiated using the function call arguments) is also treated as a candidate function.
Step 2.
-------
Select the set of viable functions that can be called from this set of candidate functions. For a candidate function to qualify as a viable function, type conversions must exist to convert each actual argument type to the type of the corresponding formal parameter.
In our example, both candidate functions can be called and are viable.
Step 3.
-------
Rank the type conversions to be applied to the arguments and use the rule of intersection to select the 'best' function from the set of viable functions. However, if both a non-template function and an instantiation of a template function are equally 'best' matched, the non-template function is given precedence over the template instantiation.
In our example,
compare(ch_arr1,ch_arr2);
type of the arguments is
char[6]
(array of 6 char). The template instantiation gives a precise match while the non-template function requires an array-to-pointer conversion. The overload therefore resolves to the template instantiation.