Is there a way in C++ to define an enum such that its values must be fully qualified when accessed?

StackOverflow https://stackoverflow.com/questions/23437650

  •  14-07-2023
  •  | 
  •  

Question

One of the things that most bothers me about C++ enums is the fact that enum values can be accessed without any context to give the reader an indication of which type is being accessed. In other words, if I have:

typedef enum Color { NONE, RED, GREEN, ... };

I can compare variables against "NONE", for example, without the need to write "Color::NONE". Is there a way to define an enum type in such a way as to require that the value be fully qualified? This is what C# does, for example.

Était-ce utile?

La solution

You can use the new enum class, but the semantics aren't the same. It's strictly part of C++ 11/14 as well.

enum class type { t1, t2, t3 };

Autres conseils

Put your enum inside a namespace with the name you want to qualify them with.

namespace Color{
  typedef enum thisNameDoesntMatter {NONE, RED, GREEN, ...};
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top