Ducktape icon indicating copy to clipboard operation
Ducktape copied to clipboard

enum -> enum class

Open Sable-20 opened this issue 1 year ago • 1 comments

What Consider changing all enums to enum classes, this produces less surprises in code as things aren't implicitly converted to types

Why Allows less surprises in code. See example below

enum Color { red, green, blue };                    // plain enum 
enum Card { red_card, green_card, yellow_card };    // another plain enum 
enum class Animal { dog, deer, cat, bird, human };  // enum class
enum class Mammal { kangaroo, deer, human };        // another enum class

void fun() {

    // examples of bad use of plain enums:
    Color color = Color::red;
    Card card = Card::green_card;

    int num = color;    // no problem

    if (color == Card::red_card) // no problem (bad)
        cout << "bad" << endl;

    if (card == Color::green)   // no problem (bad)
        cout << "bad" << endl;

    // examples of good use of enum classes (safe)
    Animal a = Animal::deer;
    Mammal m = Mammal::deer;

    int num2 = a;   // error
    if (m == a)         // error (good)
        cout << "bad" << endl;

    if (a == Mammal::deer) // error (good)
        cout << "bad" << endl;

}

Extra information: (optional) https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum

Sable-20 avatar Sep 27 '23 13:09 Sable-20

That's interesting, never knew about it until now, thanks for pointing it out. I'll ensure enum class is used in the upcoming rewrite that is yet to be pushed upstream.

aryanbaburajan avatar Sep 28 '23 04:09 aryanbaburajan