Array of pointers-to-char as an argument

Hi,

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*/

int test_int[6] = {-6, 7, 93, 4560, 7, -7000};
double test_double[4] = {-7.53434, 91233.3214, 91233.3211, 14.5};
cout << maxn(test_int, 6) << '\t' << maxn(test_double, 4) << endl;

//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.

Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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];
}

This might also be of help -> http://cplusplus.com/doc/tutorial/templates/
Thanks! Got it working now, after correcting an additional (much simpler) error in the function definition:

template <>
char* maxn<char*>(char * a[] , int n)
{
int max = 0;

for (int i = 1; i < n; i++)
{
if (strlen(a[i]) > strlen(a[max]))
max = i;
}

return a[max];
}

Thanks for the link too!
Topic archived. No new replies allowed.