c++ - 为什么我可以使用类型别名声明 const 引用?
问题描述
我有一个简单的问题:据我所知,我可以声明const
指向某个数据类型的指针或指向常量数据类型的指针,但我只能声明对常量数据类型的引用,而不能声明对数据类型的常量引用;引用已经是常量,因为它不能重新绑定到另一个对象。
所以当我尝试创建一个const ref to someDataType
我得到编译时错误。但对我来说重要的是与type alias
using typedef
or一起使用时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++ 允许使用类型别名而不是直接使用呢?
解决方案
因为标准是这样说的:
[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 折叠规则,就像引用折叠规则一样,对于使模板和类型推导可用是必不可少的。
推荐阅读
- java - CSV 文件解析问题:与 Excel 不同的时间格式(使用 Java)
- c# - 在 Razor 页面中传递 id
- node.js - 使用 Heroku 在另一个测功机上代理 API
- java - Java将for转换为while循环
- django - 确认删除的引导模式
- javascript - 在 svg 或 css 中创建仪表图
- c++ - 为什么从 STDOUT_FILENO 重定向到它的管道中读取会挂起而没有显式 endl 或关闭管道的写端?
- sql - + 二进制类型的运算符
- java - 如何删除 MPAndroidChart 中的水平线
- jekyll - Jekyll + Jemoji:如何配置表情符号大小?