为什么我可以使用type-alias声明一个const引用?

Ale*_*x24 8 c++ reference

我有一个简单的问题:我知道我可以声明const指向某个数据类型的指针或指向常量数据类型的指针,但我只能声明对常量数据类型的引用,而不能对数据类型进行常量引用; 引用已经不变的事实,因为它不能反弹到另一个对象.

所以当我尝试创建一个const ref to someDataType我得到编译时错误.但重要的是与type alias使用typedef或使用时using.例如:

#include <iostream>

int main() {

    int i{ 10 };
    //  int& const r1{ i }; // error: ‘const’ qualifiers cannot be applied to ‘int&’. Ok here.
    using rInt = int&; // or typedef int& rInt;
    const rInt r2{ i }; // why const is allowed here?
    ++r2; // this proves that the const is applied to the reference not to the object referred to.

    std::cout << r2 << std::endl; // 11

}
Run Code Online (Sandbox Code Playgroud)

正如您在上面所看到的,我可以const在该上下文中添加我认为是冗余的引用.但是为什么C++允许使用类型别名而不是直接?

eer*_*ika 12

因为标准如此说:

[dcl.ref] ...除非通过使用typedef-name([dcl.typedef],[temp.param])或decltype-specifier引入cv限定符,否则Cv限定引用的格式不正确( [dcl.type.simple]),在这种情况下,忽略cv限定符

这类似于不能声明引用引用的方式,而可以通过typedef(引用合并为一个):

int i;
int& iref = i;
//int& & irefref = iref; // not OK
using Iref = int&;
Iref& iretypedef = iref; // OK; collapses into int&
Run Code Online (Sandbox Code Playgroud)

CV-collapsing规则就像参考折叠规则一样,对于使模板和类型推导可用是必不可少的.


Nat*_*ica 5

这是常识发挥作用的情况.由于无法重新分配引用,因此它们就像它们一样const.添加const到引用声明不会添加任何内容,因此T & const禁止每[dcl.ref]/1

[...] Cv限定的引用是不正确的,除非通过使用typedef-name([dcl.typedef],[temp.param])或decltype-specifier([dcl.]来引入cv-qualifiers. type.simple]),在这种情况下,将忽略cv限定符.

您会注意到它是允许的,然后引用是typedef-namedecltype-specifier.所以,如果T是,T&那么const被忽略.如果不是这样会使通用编程变得更难.