所以我想练习使用std::forward
并创建了一个Test
有 2 个构造函数的类。1个with T&
,另一个withT&&
作为过载。T&
打印lvalue并T&&
打印rvalue以便我知道正在使用哪个构造函数。我在堆栈上创建了 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
函数并实现它,但两次都打印了rvalue x2。我究竟做错了什么?