c++ - 如何理解 C++ 标准 N3337 中的 expr.const.cast 条款 8?

标签 c++ c++11 c++17 const-cast

C++ draft standard N3337[expr.const.cast]/8 :

The following rules define the process known as casting away constness. In these rules Tn and Xn represent types. For two pointer types:

X1 is T1 cv1,1 * ⋯ cv1,N * where T1 is not a pointer type

X2 is T2 cv2,1 * ⋯ cv2,M * where T2 is not a pointer type

K is min (N,M)

casting from X1 to X2 casts away constness if, for a non-pointer type T there does not exist an implicit conversion (Clause conv) from:

T cv1,(N-K+1) * cv1,(N-K+2) *⋯ cv1,N *

to

T cv2,(M-K+1) * cv2,(M-K+2) *⋯ cv2,M *

从句看不懂,于是在C++ draft standard N4659中查找对应的从句, [expr.const.cast]/7 :

A conversion from a type T1 to a type T2 casts away constness if T1 and T2 are different, there is a cv-decomposition of T1 yielding n such that T2 has a cv-decomposition of the form

cv02P02 cv12P12cvn-12Pn-12 cvn2 U2

and there is no qualification conversion that converts T1 to

cv02P01 cv12P11cvn-12Pn-11 cvn2 U1.

但是我还是搞不懂T1,T2T之间的关系。帮帮我,谁能解释一下这个子句?

最佳答案

在旧版本中,引入了一个(大部分)任意的 T 只是为了免除

const int *p=0;
auto q=reinterpret_cast<char*>(p);  // error: casts away constness

正在从 int 更改为 char。它被有效地重写为

auto __q=reinterpret_cast<const char*>(p);  // ok
char *q=__q;  // error

较新的版本只是明确地重用了 U1 而不是发明了 T

关于c++ - 如何理解 C++ 标准 N3337 中的 expr.const.cast 条款 8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53127801/

相关文章:

c++ - 双数据类型背包

c++ - 模板特化和静态局部变量

c++ - 为什么 unique_ptr 对 auto_ptr 有重载?

c++ - 标准变体和前向声明

具有可变键数的 C++ 键值容器

c++ - 函数参数中的struct关键字,有什么区别?

c++ - std::push_back 使用起来相对昂贵吗?

c++ - 为什么迭代器不依赖于分配器? (也就是说,让迭代器变得可怕不会违反分配器的 typedef 抽象吗?)

c++ - 获取两个不同模板的产品类型

c++ - 无法在 C++17 之前的模式下使用 static constexpr 进行编译