Good evening. I'm trying to do the following:
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 tem-
plate with an array of six int value and an array of four double values.The pro-
gram 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.
Code:
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
T maxn(const T *a, const int n);
// explicit specialization
template <> char* maxn(const char *words[], const int n);
template <typename T>
T maxn(const T *a, const int n)
{
T max = a[0];
size_t i;
for(i = 1; i < n; i++)
{
if(a[i] > max)
max = a[i];
}
return max;
}
// template function should return the address of the longest string
template <> char* maxn(const char *words[], const int n)
{
size_t tam = strlen(words[0]);
char *longest;
char *str;
for(str = words[1]; str != words[n]; str++)
{
if(tam < strlen(str) )
{
tam = strlen(str);
longest = str;
}
}
return longest;
}
int main()
{
int a1[6] = {12, -56, 11, -98, 32, 21};
double a2[4] = {56.12, 78.31, -99.99, 12.11};
double dmax;
int imax;
imax = maxn(a1, 6);
dmax = maxn(a2, 4);
cout << "Largest integer value: " << imax << endl;
cout << "Largest double value: " << dmax << endl;
return 0;
}
There are lot of things going wrong there:
Code:
thames@semaht ~/C++/Templates $ g++ -g -Wall maxn.cpp -o maxn -std=c++11
maxn.cpp:10:19: error: template-id ‘maxn<>’ for ‘char* maxn(const char**, int)’ does not match any template declaration
maxn.cpp:26:19: error: template-id ‘maxn<>’ for ‘char* maxn(const char**, int)’ does not match any template declaration
maxn.cpp: In instantiation of ‘T maxn(const T*, int) [with T = int]’:
maxn.cpp:50:21: required from here
maxn.cpp:18:12: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
maxn.cpp: In instantiation of ‘T maxn(const T*, int) [with T = double]’:
maxn.cpp:51:21: required from here
maxn.cpp:18:12: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
thames@semaht ~/C++/Templates $
Please help me fix those.