Answer the question
In order to leave comments, you need to log in
An error occurred while creating an explicit specialization. Where is the mistake?
Doing exercise 6 of chapter 8 of the book "The C++ Programming Language" by Stephen Pratt
Write a template function maxn() that takes an
array of elements of type m and an integer representing the number
of elements in the array as an argument, and returns the element with the largest value. Test
it in a program that uses this pattern with an array of six
int values and an array of four double values.
The program must also include a specialization that takes an array of pointers to char
as the first argument and a number of pointers as the second, and then
returns the address of the longest string. If there is more than one line
longest, the function should return the address of the first one. Test
the specialization on an array of five pointers to strings.
I get an error in VS19 :no instance of function template "maxn" matches the specified type.
What am I doing wrong?
#include <iostream>
template <typename T>
T maxn(T arr[], int arrSize);
template <> char* maxn(const char *arr[], int arrSize);
int main()
{
return 0;
}
template <typename T>
T maxn(T arr[], int arrSize)
{
T max = arr[0];
for (int i = 1; i < arrSize; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
template <> char* maxn(const char* arr[], int arrSize)
{
char* line = arr[0];
for (int i = 0; i < arrSize; i++)
if (strlen(arr[i]) > strlen(line))
line = arr[i];
return line;
}
Answer the question
In order to leave comments, you need to log in
template <typename T>
T maxn(T arr[], int arrSize);
template <>
const char* maxn(const char* arr[], int arrSize);
char*
) are determined by the type or const char*
if the string is not going to be modified. Our function does not plan to modify strings, so explicit template specialization must work with const char*
. const char*
must be substituted everywhere in place of the template parameter T
. template <> char* maxn(const char *arr[], int arrSize);
char*
is different from the function parameter const char*
. template <>
const char* maxn<const char*>(const char* arr[], int arrSize);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question