My question is: When a variable of type int* is passed to the function template, T becomes int and not *int. When instantiating an object using type int*, T does indeed become int* (which is what I was expecting). It seems to me that the function template separates the int part from the * part, but why?
#include <iostream>
usingnamespace std;
template <typename T> // Function Template
T functionTemplate(T *param)
{
T value = 3; // T = int NOT int*
*param += value;
return *param;
}
template <class T> // Class Template
class classTemplate
{
public:
T value;
classTemplate(T param)
{
T variable = param; // T = int* Not int
value = variable;
}
};
int main()
{
int num1 = 2;
int* numpointer1 = &num1;
cout << functionTemplate(numpointer1) << endl << endl; // Calling function passing an int*
int num2 = 7;
int* numpointer2 = &num2;
classTemplate<int*> object(numpointer2); // Instantiating object with type T set as int*
cout << *(object.value) << endl << endl;
return 0;
}
I see now. This works as I was initially expecting:
1 2 3 4 5 6 7 8
T functionTemplate(T param)
{
int test = 15;
T value = &test; // T = int* As I initially expected
*param += *value;
return param;
}
It seems one of the tutorial examples I've been working through is using a function template in the same way as my initial sample program, which was confusing me.
So then is it correct that programmers sometimes deliberately separate for example the int part from the * part by using a parameter list as in my initial sample program?