3

I wrote the following code:

template <typename T>
void  myname(T* x)
{
    cout<<"x is "<<x;
}

and I Invoked:

char *p="stackOverflow";
myname(p);

It prints stackOverflow.

But if I change the template argument from (T* x) to (T x) I get the same result.

So what is the difference between the two template parameters?

void  myname (T x)  

and

void myname (T* x)
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
Whoami
  • 13,930
  • 19
  • 84
  • 140

3 Answers3

4

First case - T is deduced to char, so T* will be char*. Second case - T is deduced to char*. Differences here are in call to such function

For first case should be

myname<char>(p);

and for second

myname<char*>(p);

Also, differences will be when you use type T in function.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • Excelletanswer. if this is the case, how to pass double pointer like char ** ? – Whoami Apr 25 '13 at 11:35
  • @Whoami what do you mean? for first case use T**, for second use T, and for third case use T*. Call like `myname(&p)`; – ForEveR Apr 25 '13 at 11:42
2

The difference will be visible when you use T in your function

char *p="stackOverflow";
myname(p);

template <typename T>
void  myname(T* x)
{
    cout<<"x is "<<x;
    T t;                 // This is char now
}

However with this

template <typename T>
void  myname(T x)
{
    cout<<"x is "<<x;
    T t;                 // This is char* now
}

stardust
  • 5,918
  • 1
  • 18
  • 20
2

In both cases, the compiler deduces the template argument to generate a function that matches the function argument type char *.

In the first case, it instantiates the template with T = char giving void myname<char>(char* x).

In the second case, it instantiates it with T = char* giving void myname<char*>(char* x).

Also, note that string literals are constants, and you should never point a non-const pointer at one.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644