[英]Why universal reference have to use template for the member function instead of class?
For example: This is NOT universal reference:例如:这不是通用参考:
template<typename T>
class C {
public:
void gogo(T&& c);
};
But this is:但这是:
template<typename A>
class C {
public:
template<typename B>
void gogo(B&& par);
}
In the second snippet, B&& par
is not necessarily an universal reference.在第二个片段中,
B&& par
不一定是通用参考。 It's considered to be universal only if you let the compiler deduce B
when the call is made:只有在调用时让编译器推断
B
时,它才被认为是通用的:
C<float> c;
c.gogo(42); // T is deduced as int, `par` acts as an universal reference.
c.gogo<int>(42); // T is fixed, `par` is a regular rvalue reference.
Since in the first snippet T
is always fixed when the call is made, the reference is never universal.由于在第一个片段中
T
在调用时总是固定的,因此引用永远不会是通用的。
C<int> c; // Must specify T here, there's no way for it to be deduced.
c.gogo(42); // T is fixed, `par` is a regular rvalue reference.
This is because a universal, or a forwarding reference is, by definition an rvalue reference to a template parameter of the function call itself .这是因为根据定义,通用或转发引用是对函数调用本身的模板参数的右值引用。
Deducing template arguments from a function call [temp.deduct.call]
从函数调用中推导出模板参数 [temp.deduct.call]
A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template
转发引用是对不代表类模板的模板参数的 cv 非限定模板参数的右值引用
The standard explicitly calls out the fact that the template parameter is not a class template parameter.该标准明确指出模板参数不是类模板参数的事实。 You can actually figure it out yourself:
你实际上可以自己弄清楚:
template<typename T>
class C {
public:
void gogo(T&& c);
};
Here, goto()
is not a template function.这里,
goto()
不是模板函数。 The template here is the class.这里的模板是类。 Once the template class gets instantiated with some specific type,
gogo()
is just an ordinary, non-template class method that takes a parameter of a defined, specific type, an rvalue reference to whatever type the class template parameter is.一旦模板类被某个特定类型实例化,
gogo()
只是一个普通的非模板类方法,它接受一个已定义的特定类型的参数,一个对类模板参数是任何类型的右值引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.