返回
C++ 枚举量重定义规则缺陷发现纪实
见解分享
2023-12-27 04:30:01
无论是在软件开发实践中,还是在 C++ 标准的演进完善过程中,发现并提交 C++ 语言的 defects(规则缺陷)都具有重要的意义。缺陷的修复能促使 C++ 语言朝着更加完善、更加符合实际使用需求的方向发展。这篇文章记录了我发现并提交 C++ 核心语言标准中一个关于枚举量重定义的规则缺陷的经历,该缺陷已在 C++23 标准中得到修复。
规则缺陷的发现
在 C++ 核心语言标准草案 N4901 中,关于枚举量重定义的规定如下:
[dcl.enum]/10.3.3:
An enumeration definition defines a set of identifiers (the enumerators) that are declared as constants. Each identifier in an enumeration definition is implicitly declared as a constexpr static data member of the enumeration type.
[dcl.enum]/10.5:
If an enumeration is defined with no enumerators (that is, its defining declaration has no { }), or if an enumeration is defined with anonymous enumerators, it is an enum-class; otherwise, it is an enum-type.
在标准中,枚举量被定义为枚举类型的常量静态数据成员,枚举量重定义是指在一个枚举类型中,出现两个或多个同名的枚举量。根据上述规定,枚举类型不允许枚举量重定义。然而,在实际使用中,我们发现枚举量重定义在某些情况下是有意义的。
规则缺陷的提交
为了解决这个规则缺陷,我们向 ISO C++ 委员会提交了缺陷报告 DR2123。在报告中,我们指出了标准中关于枚举量重定义的规定存在缺陷,并提出了修改建议。修改建议如下:
[dcl.enum]/10.5:
If an enumeration is defined with no enumerators (that is, its defining declaration has no { }), or if an enumeration is defined with anonymous enumerators, it is an enum-class; otherwise, it is an enum-type.
In an enum-type, enumerators with the same identifier can be defined multiple times.
经过 ISO C++ 委员会的讨论和审议,DR2123 被接受,并被纳入 C++23 标准中。这意味着在 C++23 标准中,枚举量重定义在 enum-type 中是允许的。
缺陷修复的影响
这个规则缺陷的修复对 C++ 语言的影响是积极的。允许枚举量重定义,提高了 C++ 代码的表达能力和灵活性。在实际使用中,枚举量重定义可以用来表示具有相同底层值的多个枚举量,这在某些场景下是有用的。
总结
通过发现并提交 C++ 核心语言标准中的规则缺陷,我们为 C++ 语言的完善和发展做出了贡献。这个规则缺陷的修复提高了 C++ 代码的表达能力和灵活性,对 C++ 语言的实际使用产生了积极的影响。