模板类型的推断
下面的函数f是个模板函数,typename T。下表是,根据调用测的实参,推断出来的T的类型。
请注意下表的红字部分, f(T&& t)看起来是右值引用,但其实它会根据实参的类型,来决定T的类型,如果实参是左值,则它是左值,如果实参是右值,则它是右值。
所以可以看出来,T&可以变成const& ,f(T&& t)也可以变成const&。
f(T t) | f(const T t) | f(T& t) | f(const T& t) | f(T&& t) | f(const T&& t) | |
---|---|---|---|---|---|---|
f(1) | f<int> | f<int> | error cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int' | f<int> | f<int> | f<int> |
int i = 1; f(i); |
f<int> | f<int> | f<int> | f<int> | f<int&> | error cannot bind rvalue reference of type ‘const int&&’ to lvalue of type ‘int’ |
int& ri = i; f(ri); |
f<int> | f<int> | f<int> | f<int> | f<int&> | cannot bind rvalue reference of type ‘const int&&’ to lvalue of type ‘int’ |
const int ci = 2; f(ci); |
f<int> | f<int> | f<const int> | f<int> | f<const int&> | cannot bind rvalue reference of type ‘const int&&’ to lvalue of type ‘const int’ |
const int& rci = ci; f(rci); |
f<int> | f<int> | f<const int> | f<int> | f<const int&> | cannot bind rvalue reference of type ‘const int&&’ to lvalue of type ‘const int’ |