首页 > 解决方案 > 为什么此代码打印出 RValue 而不是 LValue

问题描述

我正在测试代码并陷入困境。

这是我的代码:

#include <iostream>

template<typename T>
void check(T&& other) {
    std::cout << "Rvalue" << std::endl;
}

template<typename T>
void check(T& other) {
    std::cout << "Lvalue" << std::endl;
}

template<typename T>
void call(T other) {
    check(std::forward<T>(other));
}

int main() {    
    std::string t = "Cool";
    call(t);
}

输出:

RValue

为什么这个“RValue”的输出?我确实传递了一个 LValue,当它转发时,它不是作为 LValue 转发的吗?为什么会调用check的RValue函数呢?

标签: c++perfect-forwarding

解决方案


std::forward正确使用,您的参数类型应该是T &&,而不是T。像这样修复它:

template<typename T>
void call(T&& other) {
    check(std::forward<T>(other));
}

然后我们得到预期的结果。

在线演示

参考_std::forward

当 t 是转发引用(声明为对 cv 非限定函数模板参数的右值引用的函数参数)时,此重载将参数转发给另一个函数,该函数具有传递给调用函数时的值类别。


推荐阅读