Class & Function Template Comparison

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?

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
34
35
36
37
#include <iostream>

using namespace 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;
}
Try:
1
2
template <typename T>  // Function Template
T functionTemplate( T pointer ) ; // instead of T* param 
If I use:

T functionTemplate(T param)

I get a compile error: cannot covert from int to int* on line 8.
Last edited on
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?
Last edited on
Yes. For instance, we could have:
1
2
template < typename T >
void foo( T value, T* pointer_to_T, const T& reference_to_const_T, std::vector<T> vector_of_T ) ;
Very cool. Thanks again :)
Topic archived. No new replies allowed.