问题
template <typename T>
void test(const T& x) {}
int a {};
int& ref = a;
const int& c_ref = a;
test(c_ref) // T = int, x = const int&
test<int&>(ref); // T = int& , x = int&
Why does the function template parameter x loses the const
qualifier?
回答1:
In the explicit (non-deduced) instantiation
test<int&>(ref);
this is the (theoretical) signature you get
void test<int&>(const (int&)& x)
which shows that the const
-qualification applies to the whole (int&)
, and not only the int
. const
applies to what is left, and if there's nothing, it applies to what is right: int&
, but as a whole - there, it applies to &
, again because const
applies to what's on its left. But there are no const
references (they aren't changeable at all, i.e., they can't rebind), the const
is dropped, and reference collapsing rules contract the two &
into one.
来源:https://stackoverflow.com/questions/64893722/function-template-parameter-loses-const-when-template-argument-is-explicity-pass