左值绑定到右值引用 [英] lvalue binding to rvalue reference

查看:95
本文介绍了左值绑定到右值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解左值如何绑定到右值引用。考虑以下代码:

I am trying to understand how lvalues bind to rvalue references. Consider this code:

#include <iostream>

template<typename T>
void f(T&& x) {
    std::cout << x;
}

void g(int&& x) {
    std::cout << x;
}

int main() {
    int x = 4;
    f(x);
    g(x);
    return 0;
}

虽然对f()的调用很好,但对g()的调用给出一个编译时错误。这种绑定仅适用于模板吗?为什么?

While the call to f() is fine, the call to g() gives a compile-time error. Does this kind of binding work only for templates? Why? Can we somehow do it without templates?

推荐答案

因为 T 是一个模板参数 T& 成为转发参考。由于引用折叠规则,对于左值和 f(T&&)变为 f(T&)对于右值, f(T&)变为 f(T&)

Since T is a template argument, T&& becomes a forwarding-reference. Due to reference collapsing rules, f(T& &&) becomes f(T&) for lvalues and f(T &&) becomes f(T&&) for rvalues.

这篇关于左值绑定到右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆