Cannot apply const to typedef reference

落花浮王杯 提交于 2019-12-05 19:11:55

There are two different issues here.

First, in:

typedef T* pointer;
typedef const pointer const_pointer;

the type of const_pointer is actually T* const, not const T*. The constness attaches to the pointer, not to the type pointed to.

Now references obey the same logic: if you make a typedef for the reference type, and try to attach const to it, it will try to apply the const to the reference type, not the referenced type. But references, unlike pointers, are not allowed to have top-level cv-qualification. If you try to mention T& const, it's a compilation error. But if you try to attach the cv-qualification through a typedef, it's just ignored.

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or *decltype-specifier *(7.1.6.2), in which case the cv-qualifiers are ignored.

([dcl.ref]/1)

So the second issue is that GCC thinks this is an error, whereas the standard clearly states that it should not be an error, it should just ignore the const. I think this is a bug in GCC. Clang does not produce an error: http://coliru.stacked-crooked.com/a/5b5c105941066708

You cannot apply const to a reference, like const(ref(type)).

But you can have a reference to a const type, like ref(const(type)).

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