为什么右值引用类型的模板参数可以绑定到左值类型?
Why a template argument of a rvalue reference type can be bound to a lvalue type?
据我所知,右值引用不能绑定到左值。 例如,
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 中阅读这篇文章通用参考资料来理解。这里有一部分:
如果某个变量或参数被声明为具有某些推导类型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
这里有一个与您的案例相关的标准摘录:
。函数模板参数类型(称为 P)...如果 P 是转发引用,参数是左值,则使用类型"对 A 的左值引用"代替 A 进行类型推断。
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 运行时错误:引用绑定到类型为"int"的空指针
- 无法将运行时类绑定到 XAML T 必须是 WinRT 类型
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 无法将类型"T&"的非常量左值引用绑定到类型"T"的右值 t++ std::atomic<T>
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 错误:对类型 'const ItemInstance' 的引用无法绑定到类型 'void' 的右值
- 没有类型结构绑定不起作用?
- 为什么"const auto [x, y]"绑定到引用类型时没有按预期运行?
- std::绑定variadic模板和自动返回类型
- 如何对绑定的成员方法进行typedef,然后将该类型用作模板参数
- 在无序映射的结构化绑定中推导类型
- 错误:在类型 "blah blah" 的绑定引用中删除限定符以初始化"some other blah blah"
- 您自己的类型的结构化绑定,不是结构或元组(通过公共成员函数)
- 使用 pybind11 绑定 typedef 类型的正确语法是什么?
- Python C++绑定类型upcast问题
- 非覆盖虚拟函数的绑定类型
- 绑定类型别名