そこで、2 つのコンストラクターを持つクラスをstd::forward
作成して使用方法を練習したいと思いました。Test
1 は withT&
で、もう1 つはT&&
as オーバーロードです。左辺値をT&
出力し、右辺値を出力するので、どのコンストラクターが使用されているかがわかります。スタック上にクラスの 2 つのインスタンスを作成しますが、驚いたことに、どちらもオーバーロードを使用しています。T&&
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
関数を使用して実装しようとしましたが、どちらも右辺値x2 を出力しました。私は何を間違っていますか?