c++ - 为什么右值引用类型的模板参数可以绑定(bind)到左值类型?

标签 c++ forwarding-reference

据我所知,右值引用不能绑定(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/

相关文章:

c++ - 结构化绑定(bind)和转发引用混合得好吗?

c++ - 为什么auto && var2不隐含右值引用?

c++ - 无法从通用引用中捕获 lambda 中的引用?

c++ - Hackerrank中的错误比较三元组代码

c++ - 公共(public)和私有(private)领域的内存分配 - GCC方式

C++ 模板 : problem with member specialization

c++ - 如何在 Qt/c++ 中使用多线程通过 Api 访问我的数据库?

c++ - 为什么 std::pair 对 const 引用和转发引用参数有两个不同的构造函数?

c++ - 如何转发打包的可变参数

c++ - 如何在 C++ 中使用 if-then 语句正确计算用户输入