Question

Section 7.2 Enumeration declarations doesn't say anything about the operator!=() and the operator==() for a scoped enumeration. But the code below compiles.

#include <iostream>

enum class Month{jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov , dec};

int main()
{
    Month a = Month::feb;
    Month b = Month::jul;
    Month c = a;

    if( a != b ) std::cout << "a |= b" << '\n';
    if( a == c ) std::cout << "a == c" << '\n';
}
Was it helpful?

Solution

The built-in operators are specified in 5.10:

The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result.

This defers the specification to that of the relational operators in 5.9; for enumerations that's specified by 5.9/5:

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.

So, as one might expect, the comparison operators are applicable to enumerations, comparing the numeric values.

OTHER TIPS

From the C++ Standard

5.10 Equality operators [expr.eq] 1 The == (equal to) and the != (not equal to) operators group left-to-right. The operands shall have arithmetic, enumeration, pointer, or pointer to member type, or type std::nullptr_t. The operators == and != both yield true or false, i.e., a result of type bool. In each case below, the operands shall have the same type after the specified conversions have been applied.

As you see enumerations independing of whether they are scoped or unscoped can be used in equality operators

The WHOLE POINT of enums is an equality (and not) test. ints have an order, 1<2, but EMPTY WHITE and BLACK (if you haev an Othello board say, it just so happens I was working on one 2 hours ago) is WHITE>BLACK, what about WHITE%EMPTY, no, but the WHOLE POINT is so I can say

switch(board.get_square(x,y)) {
    case Piece::WHITE:
        magic();
        break;
    case Piece::BLACK:
        whatever();
        break;
    default:
 }

For an enum class Piece; of course.

case is like an equality comparison I am saying:

if(board.get_square(x,y) == Piece::WHITE) {

or something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top