1

I use VS2010 which doesn't have the strongly typed enums of C++11. The strong typing I can live without, but all the same, I'd like to keep enumerations out of my class's namespace.

class Example{
    enum Color{
        red,
        green,
        blue
    };

    int Rainbows{
        Color x = red;           // this should be impossible
        Color y = Color::green;  // this is the only way at the enumerations
    }
};

My question, is what is the best way to accomplish this, pre-C++11?

Anne Quinn
  • 12,609
  • 8
  • 54
  • 101

2 Answers2

3
namespace ExampleColor {
   enum Color {
     red,
     green,
     blue
   };
}

class Example {
   int Rainbows{ExampleColor::Color x = ExampleColor::red};
};
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • `using namespace ExampleColor; Color x = red; // this should be impossible` – Spook Mar 05 '13 at 06:11
  • @Spook yes, but it's common variant of usage "scoped" enumeration before C++11. – ForEveR Mar 05 '13 at 06:12
  • Maybe. But the OP wanted the assignment `x = red;` not to be possible, but in your example it still is. Additionally, the Color is defined as a subclass - you cannot insert namespace into class, do you? – Spook Mar 05 '13 at 06:23
  • Though, I have to agree, that it's a lot easier to implement than the version with classes :) I guess, that all depends on OP's needs. – Spook Mar 05 '13 at 06:34
  • @Spook - W-well, technically yes! But if I used `using`, it'd be my fault. My goal is just to prevent the enums from being listed in the class's namespace in my IDE, so this would work. – Anne Quinn Mar 05 '13 at 06:36
1

I would try something like the following:

class Color
{
private:
    int value;

    Color(int newValue)
    {
        value = newValue;
    }

public:
    static Color red;
    static Color green;
    static Color blue;
};

Color Color::red = Color(1);
Color Color::green = Color(2);
Color Color::blue = Color(4);

int main(int argc, char * argv[])
{
    Color color = Color::red;
}
Spook
  • 25,318
  • 18
  • 90
  • 167
  • Isn't this a lot of code, for just scoping though? Each additional enum value would need to be added in two different spots. – Anne Quinn Mar 05 '13 at 06:30
  • That depends on your needs. If you need safe scoping, you'll choose my option. If you need simply the Name::Value notation, you may use ForEveR's solution. – Spook Mar 05 '13 at 06:32
  • And actually, the == and = operators seem not to be required, the default implementation should work well (removed them). – Spook Mar 05 '13 at 06:35
  • Ah, I see then! Thank you, though I'm a lazy programmer, so the less coding, the better (the actual enum I'm using assigns enums to every key on the keyboard, so it's about 120 entries) – Anne Quinn Mar 05 '13 at 06:39