为什么T不推断到int&& here这里

why T does not deduce to int&& here

本文关键字:int here 这里 为什么      更新时间:2023-10-16

下面是一个函数模板

template <class T>
void func(T&& t) {
}
func(4); // 4 is rvalue and T deduces to int

所以我的问题是为什么 T 不推断为 int&&?

我的意思是,如果T推导出为int&&

所以int&&&

&->int&&,这对我来说也很有意义!

为什么T不推断int&&

如果模板参数是引用,则通常在考虑推导如何发生之前删除引用(例外情况是针对左值、函数和数组推导引用时转发引用(。

在这种情况下,T是针对4推导的,这是一个int,所以T推导为int。生成的类型T&&int&&

请注意,表达式永远不会有引用类型。 4是类型int的右值,它不是int&&

这与一般的演绎工作方式一致:

template <class T> void foo(T );
template <class T> void bar(T const& );
foo(4); // calls foo<int>, not foo<int&&>
bar(4); // calls bar<int>, not bar<int const&>
为什么要

推论int&&?请注意,参数的类型是 T && ,而不是 T 。所以:

  • 所需的参数最终类型(类型推导的乘积(为 int &&
  • 参数的形式形式为 T &&
  • int && T &&最简单的T是什么?

答:int