joeButler
joeButler

Reputation: 1711

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

Upvotes: 7

Views: 3909

Answers (3)

ernie
ernie

Reputation: 1

I find when I use bit-wise unscoped enumerations I get the benefit of automatic conversion to int while still being able to refer to a bit as, e.g., IoType::Input given:

enum IoType
    {
    Indeterminable = 0,
    Input          = 1,
    Output         = 2,
    IOput          = Input|Output,
    };

Upvotes: 0

Daniel Frey
Daniel Frey

Reputation: 56863

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.

Upvotes: 13

Kerrek SB
Kerrek SB

Reputation: 477060

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

Upvotes: 5

Related Questions