【问题标题】:Why a template argument of a rvalue reference type can be bound to a lvalue type?为什么右值引用类型的模板参数可以绑定到左值类型?
【发布时间】:2018-04-19 03:24:42
【问题描述】:

据我所知,右值引用不能绑定到左值。 例如,

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);
}

编译器不会报错。 为什么?

【问题讨论】:

  • 因为它不是右值引用,而是forwarding reference,它适用于左值和右值。
  • 查找引用折叠

标签: c++ forwarding-reference


【解决方案1】:

您可以阅读这篇文章Universal References in 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

这里有一个与您的案例相关的excerpt from the Standard

... 函数模板参数类型(称为 P)... 如果 P 是转发引用并且参数是左值,则使用类型“对 A 的左值引用”代替 A 进行类型推导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 2018-01-13
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多