I'm brushing up on my C++ using Prata's C++ Primer Plus, doing all of the exercises as I go along. I was cruising right through them until I got to one that asked that I write two template functions. The first is easy: a template function that takes as its arguments an array of items of a generic type and an integer representing the number of items in the array and which returns the largest item in the array. Piece of cake.
For the second one, it asks that I write a specialization that takes an array of pointers-to-char as the first argument, the number of pointers as the second argument, and returns the address of the longest string. For this one I just can't seem to get the syntax right.
I've tried many things that failed. Here is my current (nonfunctioning) code:
#include <iostream>
#include <cstring>
using namespace std;
template <typename Any>
Any maxn(Any a[], int);
template char* maxn<char, int>(char *, int n);
int main()
{
/*this part works fine as long as I comment out the declaration and definition of the specialization*/
//not bothering to test the specialization because it won't even compile
return 0;
}
template <typename Any>
Any maxn(Any a[], int n)
{
Any max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
template char* maxn<char, int>(char*, int n)
{
int max = 0;
for (int i = 1; i < n; i++) {
if (strlen(*cp[i]) > strlen(*cp[i])) {
max = i;
}
}
return cp[i];
}
I'd really appreciate any help you can provide. I know I'm probably just making a really embarrassing rookie mistake, but at this point I'm getting a little frustrated with it.
template <>
char* maxn<char*>(char * a[] , int n);
//...
template <>
char* maxn<char*>(char * a[] , int n)
{
int max = 0;
for (int i = 0; i < n; i++)
{
if (strlen(a[i]) > strlen(a[i]))
max = i;
}
return a[max];
}