简体   繁体   中英

Why does the scoped enum support operator '<' by default?

Consider:

enum class Number {one, two};

if (Number::one < Number::two)
{}

My understanding is that the scoped enum needs to be cased into the underlying type or integer, and then it can be applied to operator < > ==. But it looks like the code snippet above can work without any explicit overloading operator < .

I don't see any descriptions in Enumeration declaration .

What does the C++ standard say about which operators are supported for a scoped enum by default?

If you are referring to the "usual arithmetic conversions", then yes they are done when the arguments are arithmetic or enumeration types. It's just that there is a special bullet there for scoped enums:

[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.

So this case is covered here. Since the two operands are of the same scoped enum type, they are just checked to hold the specific relation in the fashion one would expect.

My understanding is that scoped enum needs to be cased into underlying type or integer then it can be applied to operator < > ==.

Not when both of them are scoped enums. SomeScopedEnum < SomeInt is ill-formed, you're right in that case.

[expr.rel]p6 :

If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield true if the specified relationship is true and false if it is false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM