### In a Function template

Do I have to use T as a parameter type in order for the compiler to deduce it?

For example this:

 ``123456789`` ``````template T max(T x[], const int& len) { T maximum(x[0]); for(int i = 1; i < len; i++) if(maximum < x[i]) maximum = x[i]; return maximum; } ``````

If I take out the T as type of x[] it will not compile because it can't deduce T right?

Like so

 ``123456789`` ``````template T max(long x[], const int& len) { T maximum(x[0]); for(int i = 1; i < len; i++) if(maximum < x[i]) maximum = x[i]; return maximum; } ``````

I tried and it wouldn't compile but I just wanna make sure that it is necessary that I always have to use my template parameter as a parameter type in order for
my compiler to deduce the type?
This compiles and works fine:

 ``1234567891011121314151617181920212223`` ``````#include #include #include using namespace std; template T max(T x[], const int& len) { T maximum(x[0]); for(int i = 1; i < len; i++) if(maximum < x[i]) maximum = x[i]; return maximum; } int main() { long values[4] = { 7, 5, 9, 6 }; long max_value = max(values, 4); cout << "max_value : " << max_value << endl; return 0; }``````
Last edited on
See you used T as the parameter for x[]. My question is if you do take that away it will not compile right?
There is no point in having a template method then if you're not using the defined type.
This is how I'd do it: (note you need to use -std=c++11 as compiler flag because this code is C++11 standard)

 ``12345678910111213141516`` ``````#include #include using namespace std; int main() { vector values = { 2, 4, 9, 6, 7, 8 }; long max = 0; for (long value : values) max = value > max ? value : max; cout << "max_value : " << max << endl; return 0; } ``````
I understand that except I just wanted to know. Thanks for clearing up my confusion xD
Topic archived. No new replies allowed.