Modify Listing 8.14 so that it uses two template functions called SumArray() to return the sum of
Question:
Modify Listing 8.14 so that it uses two template functions called SumArray() to return the sum of the array contents instead of displaying the contents. The program now should report the total number of things and the sum of all the debts.
Consider this function call:
ShowArray(things, 6);
The identifier things is the name of an array of int, so it matches the following template
with T taken to be type int:
template // template A
void ShowArray(T arr[], int n);
Next, consider this function call:
ShowArray(pd, 3);
Here, pd is the name of an array of double *.This could be matched by Template A:
template // template A
void ShowArray(T arr[], int n);
Here, T would be taken to be type double *. In this case, the template function would
display the contents of the pd array: three addresses.The function call could also be
matched by Template B:
template // template B
void ShowArray(T * arr[], int n);
In this case, T is type double, and the function displays the dereferenced elements *arr[i]—that is, the double values pointed to by the array contents. Of the two templates, Template B is the more specialized because it makes the specific assumption that the array contents are pointers, so it is the template that gets used.
Here’s the output of the program in Listing 8.14:
Listing Mr. E's counts of things:
template A
13 31 103 301 310 130
Listing Mr. E's debts:
template B
2400 1300 1800
If you remove Template B from the program, the compiler then uses Template A for listing the contents of pd, so it lists the addresses instead of the values.Try it and see.
In short, the overload resolution process looks for a function that’s the best match. If there’s just one, that function is chosen. If more than one are otherwise tied, but only one is a non template function, that non template function is chosen. If more than one candidate are otherwise tied and all are template functions, but one template is more specialized than the rest, that one is chosen. If there are two or more equally good non template functions, or if there are two or more equally good template functions, none of which is more specialized than the rest, the function call is ambiguous and an error. If there are no matching calls, of course, that is also an error.
Step by Step Answer: