
Problem with templates
I'm trying an exercise in a book I read, which basically says "Write a template function that takes as an argument an array of five items of type T, and returns the largest item. Test it in a program with an array of 5 int values and 5 double values."
I've tried everything, but did not get it to work. There is my code:
Code:
#include <iostream>
using namespace std;
template <typename T>
T max5(T,int);
int main()
{
int numbers[5] = {0};
for (int i = 0; i < 5; i++)
{
cout << "Enter the number for element num " << (i+1) << "\n";
cin >> numbers[i];
}
cout << "The largest number in the array is: ";
int max = max5(numbers, 5);
cout << max << "\n";
return 0;
}
template <typename T>
T max5(T arr[],int n)
{
T max = 0;
for (int i=0; i<n; i++)
if arr[i]>max
max = arr[i];
return max;
}
I get an error, saying:
.\Source1.cpp(14) : error C2440: 'initializing' : cannot convert from 'int *' to 'int'
There is no context in which this conversion is possible
Line 14 is:
Code:
int max = max5(numbers, 5);
BTW, I defined the maximum number as int only becuase I don't know how to tell the compiler to check wheter it is an int, double, just as the exercise says.

The function will fail, or rather won't work, if all the numbers are negative, so I'd recommend changing
>> T max = 0;
to
>> T max = arr[0];
or whatever it was called, and then continuing with the loop from i=1
Also,
>> if arr[i]>max
shouldn't that be
>> if (arr[i]>max )

Thanks, I always forget that if statements have to be in brackets. Anyway, its not working.

Your prototype is different than the function definition. Make sure they match.

This isn't directly related to your problem, but there's a trick you can use with template parameter deduction to simplify the use of your function a bit:
Code:
template <typename T>
T max5(T,int);
can change to
Code:
// change the function prototype
template <typename T, int n>
T max5(T (&)[n] );
and the function definition changes accordingly
Code:
template <typename T>
T max5(T arr[],int n)
{
T max = 0;
for (int i=0; i<n; i++)
if arr[i]>max
max = arr[i];
return max;
}
to
Code:
template <typename T, int n>
T max5(T (&arr)[n] )
{
T max = 0;
for (int i=0; i<n; i++)
if (arr[i]>max)
max = arr[i];
return max;
}
Then change your call from
Code:
int max = max5(numbers, 5);
to
Code:
int max = max5(numbers);
in short, you can "deduce" the size of a statically sized array without needing to do any work. The prototype might look slightly more cryptic, but should make actual use of the function a bit easier :)

Thanks Bench82, that did the job, though I can't really understand what you've done. Am I passing a reference, instead of the array? I hope you can explain it to me.