为什么右值引用作为左值引用传递? [英] Why rvalue reference pass as lvalue reference?

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

问题描述

pass()参考参数,并将其传递给 reference ,但是右值参数实际上称为 reference(int&)代替 reference(int&),这是我的代码段:

pass() reference argument and pass it to reference, however a rvalue argument actually called the reference(int&) instead of reference(int &&), here is my code snippet:

#include <iostream>
#include <utility>
void reference(int& v) {
    std::cout << "lvalue" << std::endl;
}
void reference(int&& v) {
    std::cout << "rvalue" << std::endl;
}
template <typename T>
void pass(T&& v) {
    reference(v);
}
int main() {
    std::cout << "rvalue pass:";
    pass(1);

    std::cout << "lvalue pass:";
    int p = 1;
    pass(p);

    return 0;
}

输出为:

rvalue pass:lvalue
lvalue pass:lvalue

对于 p ,根据引用折叠规则很容易理解,但是为什么模板函数通过 v 转换为 reference()作为左值?

For p it is easy to understand according to reference collapsing rule, but why the template function pass v to reference() as lvalue?

推荐答案

template <typename T>
void pass(T&& v) {
    reference(v);
}

您在这里使用转发参考还不错,但事实是现在名称为 v ,它被视为 rvalue引用 lvalue

You are using a Forwarding reference here quite alright, but the fact that there is now a name v, it's considered an lvalue to an rvalue reference.

简单地说,任何具有名称的东西都是 lvalue 。这就是为什么需要完美转发才能获得完整语义的原因,请使用 std :: forward

Simply put, anything that has a name is an lvalue. This is why Perfect Forwarding is needed, to get full semantics, use std::forward

template <typename T>
void pass(T&& v) {
    reference(std::forward<T>(v));
}

什么 std :: forward< T> 只是要做类似的事情

What std::forward<T> does is simply to do something like this

template <typename T>
void pass(T&& v) {
    reference(static_cast<T&&>(v));
}

请参见

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

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