据我所知,右值引用不能绑定(bind)到左值。 例如,
void func(Foo &&f) {}
int main() {
Foo f;
func(f);
}
编译器提示: 错误:无法将“Foo&&”类型的右值引用绑定(bind)到“Foo”类型的左值
但是,为什么右值引用类型的模板参数可以绑定(bind)到左值? 例如,
template <typename T> void funcTemp(T &&arg) {}
int main() {
Foo f;
funcTemp(f);
}
编译器不会提示该错误。 为什么?
最佳答案
您可以阅读这篇文章Universal References in C++11去理解。这是其中的一部分:
If a variable or parameter is declared to have type T&& for some deduced type T, that variable or parameter is a universal reference.
Widget&& var1 = someWidget; // here, “&&” means rvalue reference auto&& var2 = var1; // here, “&&” does not mean rvalue reference template<typename T> void f(std::vector<T>&& param); // here, “&&” means rvalue reference template<typename T> void f(T&& param); // here, “&&”does not mean rvalue reference
这里是与您的案例相关的 excerpt from the Standard :
... function template parameter type (call it P) ... If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction.
关于c++ - 为什么右值引用类型的模板参数可以绑定(bind)到左值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49912221/