考虑:
enum class Number {one, two};
if (Number::one < Number::two)
{}
我的理解是,作用域枚举需要被大小写成底层类型或整数,然后才能应用到运算符<>==上。但看起来上面的代码片段可以在没有任何显式重载运算符 <
的情况下工作.
我在 Enumeration declaration 中没有看到任何描述.
C++ 标准对作用域枚举默认支持哪些运算符有什么规定?
最佳答案
如果您指的是“通常的算术转换”,那么当参数是算术或枚举类型时,它们就会完成。只是对于作用域枚举有一个特殊的项目符号:
[expr]
11 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
- If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
所以这里涵盖了这个案例。由于这两个操作数具有相同的作用域枚举类型,因此只需检查它们以按照人们期望的方式保持特定关系。
关于c++ - 为什么作用域枚举默认支持运算符 '<'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54403632/