Hi,
I'm currently working my way through "C++ Primer Plus 5th-Edition" by Stephen Prata.
However, I'm stuck on Question 5, chapter 8. I can't seem to get the specialized
function to work. When i compile the code (in Code::blocks), i get the following errors:
5-make-a-template_and_specialization.cpp|16|error: template-id ‘maxn<char*>’
for ‘char* maxn(const char*, int)’ does not match any template declaration|
5-make-a-template_and_specialization.cpp|53|error: template-id ‘maxn<char*>’
for ‘char* maxn(const char*, int)’ does not match any template declaration|
||=== Build finished: 2 errors, 0 warnings ===|
Can anyone tell me what it is i'm doing wrong and how i can fix it?
Many thanks.
Regards, EightBit.
Here is the Question:
Write a template function maxn() that takes as its arguments an array of items of type T
and an integer representing the number of elements in the array and that returns the
largest item in the array. Test it in a program that uses the function template with an
array of six int value and an array of four double values. The program should also
include a specialization that takes an array of pointers-to-char as an argument and the
number of pointers as a second argument and that returns the address of the longest
string. If multiple strings are tied for having the longest length, the function should
return the address of the first one tied for longest. Test the specialization with an array of
five string pointers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <cstring> // for the strlen() function
template <typename T>
T maxn(const T * ar, int n);
template <> char * maxn<char*>(const char * ar, int n); // line 16.
int main()
{
using namespace std;
const char * cities[5] = // array of pointers to 5 strings
{
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
double ar1[4] = {2.2, 4.4, 18.18, 23.23};
int ar2[6] = {17, 67, 45, 33, 29, 77};
double max_double = maxn(ar1, 4);
int max_int = maxn(ar2, 6);
cout << "Largest double is: " << max_double << endl;
cout << "Largest int is: " << max_int << endl;
const char * ptr = maxn(cities, 5);
cout << "The largest string is: " << ptr << endl;
cout << "\nDone!\n";
cin.get();
return 0;
}
template <class T>
T maxn(const T * ar, int n)
{
T biggest = ar[0];
for (int i = 1; i < n; i++)
{
if (ar[i] > biggest)
biggest = ar[i];
}
return biggest;
}
template <> char * maxn<char*>(const char * ar, int n) // line 53
{
char * temp = str[0];
for (int i = 1; i < n; i++)
{
if (strlen(str[i]) > strlen(temp))
char * temp = str[i];
}
return temp;
}
|