Template functions

This does not even compile and I cannot figure out why. It's got quite a list of errors for being such a small peice of code...

"Illegal use of type T as expression"
some others

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>

using namespace std;

template<typename T>
T MaxFunc(T Arr[], int sz)
{
	T Temp[sz] = T Arr[0];

	for (int i = 1; i < sz; i++)
	{
		if (T Arr[i] > Temp)
		{
			Temp = T[i];
		}
	}

	return(Temp[]);
}

int main()
{
	int IntArr[5] = { 4, 1, 13, 3, 2 };
	double DoubleArr[5] = { 1.14, 8.1, 5.2, 2.3 };
	string StringArr[5] = { "the", "student", "is", "in", "class" };


	cout << MaxFunc<int>(IntArr, 5);
	cout << MaxFunc<double>(DoubleArr, 5);
	cout << MaxFunc<string>(StringArr, 5);
}
So replace T with double. Now consider line 9/13/15. Would they make sense if T is double?

Line 19 doesn't make sense. I guess that Temp shouldn't be an array.

I suggest that you implement that function with a real type like int/double and if that works use the template.
line 9: declare a variable, not array, of type T
line 13: Arr[i] > ..., not T Arr[i] > ...
line 19: return array member, not whole array
line 24-26: the array size is redundant as the array is written 'by hand'
line 29-31: the data-type qualification for template functions is not strictly needed, the compiler can deduce it from the parameter types but for classes/structs yes, they're required
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
using namespace std;

template<typename T>
T MaxFunc(T Arr[], int sz)
{
	T maximum = Arr[0];

	for (int i = 1; i < sz; i++)
	{
		if ( Arr[i] > maximum)
		{
			maximum = Arr[i];
		}
	}

	return maximum;
}

int main()
{
	int IntArr[] = { 4, 1, 13, 3, 2 };
	double DoubleArr[] = { 1.14, 8.1, 5.2, 2.3 };
	string StringArr[] = { "the", "student", "is", "in", "class" };


	cout << MaxFunc(IntArr, 5)<<"\n";
	cout << MaxFunc(DoubleArr, 5)<<"\n";
	cout << MaxFunc(StringArr, 5)<<"\n";
}

First time learning/tying to use Templates, can you tell? Thanks so much
Topic archived. No new replies allowed.