Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function template parameter loses const when template argument is explicity passed?

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?

like image 733
Vegeta Avatar asked Jan 25 '23 14:01

Vegeta


1 Answers

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.

like image 85
lubgr Avatar answered May 10 '23 22:05

lubgr