完美的转发

完美转发需要转发引用以保留参数的 ref 限定符。此类引用仅出现在推断的上下文中。那是:

template<class T>
void f(T&& x) // x is a forwarding reference, because T is deduced from a call to f()
{
    g(std::forward<T>(x)); // g() will receive an lvalue or an rvalue, depending on x
}

以下不涉及完美转发,因为 T 不是从构造函数调用中推导出来的:

template<class T>
struct a
{
    a(T&& x); // x is a rvalue reference, not a forwarding reference
};

Version >= C++ 17

C++ 17 将允许推断类模板参数。上例中的 a 的构造函数将成为转发引用的用户

a example1(1);
  // same as a<int> example1(1);

int x = 1;
a example2(x);
  // same as a<int&> example2(x);