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

♀尐吖头ヾ 提交于 2021-02-08 15:38:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!