在他的书Effective Modern C++,Item 1: Understand template type deduction部分,Scott Meyers在讨论Case 1: ParamType is a Reference or Pointer, but not a Universal Reference
时说了以下内容这些例子都是左值引用参数,但是类型推导有效 右值引用参数的方式完全相同。当然,只有右值 参数可以传递给右值引用参数,但该限制 与类型推导无关。
引用段落前一节中给出的左值引用示例如下。
如果这是我们的模板,
template<typename T>
void f(T& param); // param is a reference
我们有这些变量声明,
int x = 27; // x is an int
const int cx = x; // cx is a const int
const int& rx = x; // rx is a reference to x as a const int
各种调用中param和T的推导类型如下:
f(x); // T is int, param's type is int&
f(cx); // T is const int, param's type is const int&
f(rx); // T is const int, param's type is const int&
问题: 对我来说,上面引用的段落由于以下原因有点令人困惑。
如果我尝试锻炼自己,处理右值引用的案例 1 示例,它应该是什么样子?可能像下面这样?
template<typename T>
void f(T&& param); // param is an rvalue reference
但是这个case不是和Case 2: ParamType is a Universal Reference一样吗?
右值引用如何在案例 1 中显示而不自动成为通用/转发引用,因为这是在类型推导的上下文中?
理解这一点的一种方法可能是将其映射到案例 2 子案例 2,其中初始化表达式是右值。在那种情况下,它被指定像案例 1 一样工作。所以这可能是从案例 2 到案例 1 的循环。