3

I've got the following program:

#include<stdio.h>
template<class T> void f(T t) { 
    t += 1; 
}
template<class T> void g(T &t) {
    t += 10;
}
int main()
{
    int n=0;
    int&i=n;
    f(i);
    g(i);
    printf("%d\n",n);
    return 0;
}

I expect that because i is a reference to n, so I expect that the template function f should get int& for template type T. But in fact it doesn't. The output of the program is 10, not 11 as I expected.

So my question is, for f, why T matches int but not int& of variable i? What's the rule behind here?

Thanks.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

4

Template deduction never deduces a reference type unless you use a forwarding reference. So your calls to f and g both deduce T as int.

Also, an expression never has reference type. i and n as expressions are identical. They have type int and value category lvalue.

The code int n = 0; int &i = n; is exactly the same as int i = 0; int &n = i;, except for decltype(1). It creates one object with two names, i and n.

Even if you did use a forwarding reference in your code, e.g. template<class T>void h(T&&t), the calls h(i) and h(n) would deduce the same way.

This symmetry is why you see many comments on the What is a reference? megathread present references as I have just now, and we consider the description "a reference is a pointer that automatically dereferences" to be misleading.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365