简体   繁体   中英

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??

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 #define s as you can put them into different namespaces or classes (as seen above) and that is something the preprocessor can not do/handle.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM