因此,我想练习的用法,std::forward并创建了Test具有2个构造函数的类。1个带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 …Run Code Online (Sandbox Code Playgroud)