据我所知,右值引用不能绑定到左值。
例如。,
void func(Foo &&f) {}
int main() {
Foo f;
func(f);
}
编译器抱怨:
错误:无法将“Foo&&”类型的右值引用绑定到“Foo”类型的左值
但是,为什么右值引用类型的模板参数可以绑定到左值?
例如。,
template <typename T> void funcTemp(T &&arg) {}
int main() {
Foo f;
funcTemp(f);
}
编译器不会抱怨该错误。
为什么?
你可以阅读这篇文章C++11 中的通用引用 https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers去理解。这是其中的一部分:
如果变量或参数被声明为具有类型T&&对于一些推导类型T,该变量或参数是通用引用。
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
这是与您的案例相关的摘自标准 http://timepp.github.io/doc/cpp14/temp.deduct.call.html:
...函数模板参数类型(称之为P)...如果P是转发引用并且参数是左值,则使用类型“对A的左值引用”代替A进行类型推导。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)