c++ - 为什么作用域枚举默认支持运算符 '<'?

标签 c++ enums

考虑:

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/

相关文章:

c# - 将整数发送到 Android 后台应用程序

c++ - 在 C++ 中使用枚举作为模板类型参数

object - 如何在 Go 中创建键值的枚举/映射

python - 如何在 cython 中访问枚举?

c++ - 从 .dat 文件中仅提取几列

c++ - 解析一个位域参数,如何解析unsigned long中的 "discard"位?

powershell - 如何将字符串转换为枚举?

c# - 在 switch 语句中我们可以在 C# 中使用枚举吗

c++ - 按值传递的变量的拷贝会保留在内存中吗?

c++ - 是否可以将 reinterpret_cast unsigned char 数组移植为仅包含 C++ 中 unsigned chars 成员的结构指针