我正在阅读有关完美转发的内容,这是我学到的让我困惑的东西:
当您尝试实现完美转发时,您将执行以下操作:
template<class T> // If I were to call foo with an l-value int, foo would look
void foo(T &&x); // like this: void foo(int& &&x)
然后我想,等等,这是否意味着如果我这样做:
template<class T> // If I were to call foo with an l-value int, foo would look
void foo(T x); // like this: void foo(int& x);
但事实并非如此。foo相反,看起来像这样:void foo(int x);
我的问题:为什么在完美转发函数中,T 变成了 T& 或 T&&,但在另一个函数中,T 不是引用?有人可以告诉我这方面的具体规则吗?我需要一些澄清!
模板参数T
可以推导为引用类型only如果它出现在以下形式的函数参数中T&&
形式的函数模板:
-
template<class T> void f(T x)
- will deduce
T
as an object type (and x
is an object type so is passed by value)
-
template<class T> void f(T& x)
- will deduce
T
as an object type (and then x
has lvalue reference type)
-
template<class T> void f(T&& x)
- will deduce
T
as
-
either左值引用(所以
x
由于引用折叠规则,具有左值引用类型)
-
or作为对象类型(所以
x
具有右值引用类型)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)