の使用法に関するこの例std::forward
は、私を困惑させます。これは私の編集版です:
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
struct A{
A(int&& n) { cout << "rvalue overload, n=" << n << "\n"; }
A(int& n) { cout << "lvalue overload, n=" << n << "\n"; }
};
template<typename> void template_type_dumper();
template<class T, class U>
unique_ptr<T> make_unique(U&& u){
//Have a "fingerprint" of what function is being called
static int dummyvar;
cout<<"address of make_unique::dummyvar: "<<&dummyvar<<endl;
//g++ dumps two warnings here, which reveal what exact type is passed as template parameter
template_type_dumper<decltype(u)>;
template_type_dumper<U>;
return unique_ptr<T>(new T(forward<U>(u)));
}
int main()
{
unique_ptr<A> p1 = make_unique<A>(2); // rvalue
int i = 1;
unique_ptr<A> p2 = make_unique<A>(i); // lvalue
}
出力は
address of make_unique::dummyvar: 0x6021a4
rvalue overload, n=2
address of make_unique::dummyvar: 0x6021a8
lvalue overload, n=1
参照に関する警告template_type_dumper
は、最初のインスタンス化ではそれを示し、2 番目のインスタンス化ではdecltype(u) = int&&
とを示します。U = int
decltype(u) = int&
U = int&
予想どおり 2 つの異なるインスタンス化があることは明らかですが、それは私の質問です。
- ここでどのよう
std::forward
に働くことができますか?最初のインスタンス化では、そのテンプレート引数は明示的U = int
に です。右辺値参照を返す必要があることをどのように知ることができますか?U&&
代わりに指定するとどうなりますか? make_unique
右辺値参照を取るように宣言されています。なぜ左辺値参照になることがu
できますか? 私が見逃している特別なルールはありますか?