4

I have an enum, and a couple of vectors of some of the contents of the enum. I want to change the enum to an enum class, for type safety, but I'm getting errors. Consider the following snippet:

#include <vector>

enum Colour {
        red,
        green,
        blue
};

int main() {
        const std::vector<Colour> something { red, green };
        return 0;
}

It works fine. However, if I change the enum to an enum class, I get errors such as error: ‘green’ was not declared in this scope. What can I do?

Moonchild
  • 483
  • 1
  • 4
  • 15

1 Answers1

6

Use Color::green for enum classes.

v78
  • 2,803
  • 21
  • 44
  • So I have to do that every time I refer to an instance of an enum class? I'm starting to think they're not really worth it. – Moonchild Oct 30 '16 at 07:05
  • 4
    Why, It makes the code more readable? And enum class is safer than plain enums btw. – v78 Oct 30 '16 at 07:08
  • It seems more readable to me to say `thecolour = red` than `thecolour = Colour::red`. `Colour::` looks like useless junk. – Moonchild Oct 30 '16 at 07:14
  • 2
    red might be defined elsewhere, like in an external library. It's a trade off, a bit more typing for some type safety. – radcore Oct 30 '16 at 07:38
  • But whatever variable you're using will already be of type `Colour`, so it *can't* be assigned to something of another type, right? – Moonchild Oct 30 '16 at 07:45
  • @Elronnd, No, plain enums in c++ are just numbers. http://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum – v78 Oct 30 '16 at 07:59