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:

1
2
3
4
5
6
7
8
9
template<typename T> 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

1
2
3
4
5
6
7
8
9
template<typename T> 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
#include <map>

using namespace std;

template<typename T> 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<long>(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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

using namespace 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;
}
I understand that except I just wanted to know. Thanks for clearing up my confusion xD
Topic archived. No new replies allowed.