Originally Posted by
cpjust
You specify the Any template parameter as the return type & first parameter of the function, but when you specialized it you only specialized the first parameter as a char*[] but not the return type.
Then you need to change your code, because right now it's specialized on an array of strings, not a single string.
Here is the entire code:
Code:
//prototypes
template <class Any>
Any maxn(Any ar[], int n);
template <> Any maxn(char ar[], int n);
int main() {
using namespace std;
int box1[6] = {5, 7, 3, 1, 8, 14};
double box2[4] = {34.54, 12.656, 78.44, 66.08};
char * box3[5] = {"Hello World!", "It's a great day.", "The weather is sunny.",
"How are you?", "Have a good day."};
cout << "Use maxn() function for integers. Largest element in the array ";
cout << "of integers is: " << maxn(box1, 6) << endl;
cout << "Use maxn() function for double values. Largest element in the array ";
cout << "of double values is: " << maxn(box2, 4) << endl;
cout << "Use maxn() function for array of char *. Return address of the longest ";
cout << "string: " << maxn(box3, 5) << endl;
system("pause");
return 0;
}
template <class Any>
void maxn(Any ar[], int n) {
using namespace std;
Any temp = ar[0];
for(int i = 1; i < n; i++) {
if(temp < ar[i]) {
temp = ar[i]; } }
return temp;
}
template <> Any maxn(char ar[], int n) {
using namespace std;
char * temp = ar[0];
for(int i = 1; i < n; i++) {
if(strlen(temp) < strlen(ar[i])) {
temp = ar[i]; } }
return *temp;
}
The specialization for the array of pointer-to-char needs to return the address of the longest string.