Do I have to use T as a parameter type in order for the compiler to deduce it?
For example this:
1 2 3 4 5 6 7 8 9
template<typename T> T max(T x[], constint& 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
1 2 3 4 5 6 7 8 9
template<typename T> T max(long x[], constint& 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 is how I'd do it: (note you need to use -std=c++11 as compiler flag because this code is C++11 standard)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <vector>
usingnamespace std;
int main() {
vector<long> 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;
}