首页 > 解决方案 > 为什么我可以使用类型别名声明 const 引用?

问题描述

我有一个简单的问题:据我所知,我可以声明const指向某个数据类型的指针或指向常量数据类型的指针,但我只能声明对常量数据类型的引用,而不能声明对数据类型的常量引用;引用已经是常量,因为它不能重新绑定到另一个对象。

所以当我尝试创建一个const ref to someDataType我得到编译时错误。但对我来说重要的是与type aliasusing typedefor一起使用时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

}

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

标签: c++reference

解决方案


因为标准是这样说的:

[dcl.ref] ... Cv 限定的引用格式错误,除非通过使用 typedef-name ([dcl.typedef], [temp.param]) 或 decltype-specifier ( [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&

CV 折叠规则,就像引用折叠规则一样,对于使模板和类型推导可用是必不可少的。


推荐阅读