Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best alternative for scoped enums - Pre C++11

I'd like to start using enums in a few places within my code, but I have an issue with previous declarations from the compiler. How the enums are currently declared makes the most sense to me:

What's the best way to avoid a situation like this?

enum score_methods_t {NONE,ABS_FROM_PERFECT,ERROR_SQUARED};
enum scale_methods_t {NONE,CASES_MULTIPLIER,RANGE_MULTIPLIER};

Should I just make everything unique, or scope with namespace? I'd like to use the enum types within a class and NONE is the most descriptive name!

Also is the reason the enums clash is because essentially thay are just #defines under the hood??

like image 486
joeButler Avatar asked Oct 09 '13 23:10

joeButler


2 Answers

In pre-C++11 times, I used:

struct score_methods { enum type { NONE, ABS_FROM_PERFECT, ERROR_SQUARED }; };

which means you always have score_methods::type for the actual enum type and score_methods::NONE, etc. for the values.

Also, no, they are not just #defines as you can put them into different namespaces or classes (as seen above) and that is something the preprocessor can not do/handle.

like image 51
Daniel Frey Avatar answered Oct 15 '22 16:10

Daniel Frey


You can always put the enums in a class:

struct Score
{
     enum Method { None, AbsFromPerfect, ErrorSquared };
};

Usage:

void foo(Score::Method m);

foo(Score::None);
like image 42
Kerrek SB Avatar answered Oct 15 '22 17:10

Kerrek SB