为什么我的代码打印右值 2 次而不是右值和左值?
Why is my code printing rvalue 2 times instead of rvalue & lvalue?
所以我想练习std::forward
的用法,并创建了一个具有 2 个构造函数的Test
类。 一个带有T&
,另一个带有T&&
作为重载。T&
打印左值,T&&
打印右值,所以我知道正在使用哪个构造函数。我在堆栈上创建了 2 个类实例,令我惊讶的是,这两个实例都使用了T&&
重载。
#include <iostream>
#include <type_traits>
#include <utility>
template <class T> auto forward(T &&t) {
if constexpr (std::is_lvalue_reference<T>::value) {
return t;
}
return std::move(t);
}
template <class T> class Test {
public:
Test(T &) { std::cout << "lvalue" << std::endl; };
Test(T &&) { std::cout << "rvalue" << std::endl; };
};
int main() {
int x = 5;
Test<int> a(forward(3));
Test<int> b(forward(x));
return 0;
}
我尝试使用原始的std::forward
函数并实现它,但两次它都打印了rvaluex2。我做错了什么?
您的问题源于返回类型forward
。 您使用auto
作为返回类型,这不会为您推断出引用。 这意味着当你返回时,无论它从哪个分支返回,你都按值返回,这意味着你有一个 prvalue。
您需要的是decltype(auto)
,以便返回右值或左值引用,具体取决于 return 语句。 用
template <class T> decltype(auto) forward(T &&t) {
if constexpr (std::is_lvalue_reference<T>::value)
return t;
else
return std::move(t);
}
为您提供输出:
rvalue
lvalue
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么我的代码在输出中增加了93天
- 0-1背包代码中的错误.我的代码中有什么错误
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 我的代码运行良好,但在游戏循环中中断
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 我的代码中的意外价值以及我如何修复它
- 为什么 rand 不在我的代码中生成随机数?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- 无法找出我的代码中的内存泄漏
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- 我正在尝试创建一个菜单,但我的代码一直在循环