Why C++ template type match doesn't retrieve reference qualifier '&'?

点点圈 提交于 2021-02-05 05:56:12

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42430121/why-c-template-type-match-doesnt-retrieve-reference-qualifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!