【发布时间】:2021-05-20 01:28:12
【问题描述】:
我目前正在学习 C++ 中的完美转发,但遇到了一些让我感到困惑的事情。很确定这是一件愚蠢的事情。当我在左值上使用 std::forward 时,它使用了右值函数。这是一个非常糟糕的解释,所以我只显示代码。
#include <iostream>
void check(int&& other) {
std::cout << "Rvalue" << std::endl;
}
void check(int& other) {
std::cout << "Lvalue" << std::endl;
}
void call(int& other) {
check(std::forward<int>(other));
}
int main()
{
int i = 4;
call(i);
}
这会输出“右值”。请帮助我理解原因。
【问题讨论】:
-
使用
std::forward的唯一原因在于接受通用模板引用template<T> void func(T&& other)的方法。话虽如此,这个问题写得很好,值得回答。 -
这能回答你的问题吗? What's the difference between std::move and std::forward There's an answer of mine there 我对
std::forward和std::move做了相同的解释步骤,我认为这对两者都有很多见解。