为什么C ++模板类型匹配不检索引用限定符'&'? [英] Why C++ template type match doesn't retrieve reference qualifier '&'?

查看:59
本文介绍了为什么C ++模板类型匹配不检索引用限定符'&'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序:

#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 是对 n 的引用,所以我希望模板函数 f 应该得到 int&(用于模板类型 T ).但实际上并非如此.程序的输出是 10 ,而不是我期望的 11 .

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.

所以我的问题是,对于 f ,为什么 T 匹配变量<代码>我?这里的规则是什么?

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

谢谢.

推荐答案

除非您使用转发引用,否则模板推导永远不会推导引用类型.因此,您对 f g 的调用都会推断出 T int .

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.

此外,表达式永远不会具有引用类型. i n 是相同的表达式.它们具有类型 int 和值类别 lvalue .

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

代码 int n = 0;int &i = n;int i = 0; 完全一样int& n = i; ,但 decltype(1).它创建一个具有两个名称的对象,分别是 i n .

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.

即使您确实在代码中使用了转发引用,例如 template< class T> void h(T& t),调用 h(i) h(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.

这篇关于为什么C ++模板类型匹配不检索引用限定符'&amp;'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆