tags:

views:

49

answers:

5

I want something like

enum EnumType {val1 = -1, val2 = 1};
enum EnumType2 {val1 = 1, val2 = -1};

In particular, val1 and val2 depend on the enumerated type--EnumType or EnumType2.

So I eventually want to be able to say something like

EnumType x = val1;
EnumType2 y = val1;

and have x and y have different values.

Is the foregoing possible?

+1  A: 

Well, val1 and val2 are ambiguous, (since they could refer to either EnumType). You can enclose the enums in a namespace or struct, so you can differentiate them like this:

namespace enums1
{
 enum EnumType {val1 = -1, val2 = 1};
}

namespace enums2
{
 enum EnumType {val1 = 1, val2 = -1};
}

So you can then say:

enums1::EnumType x = enums1::val1;
enums2::EnumType y = enums2::val1;
Charles Salvia
A: 

Not if they have the same name. If you give them a different name, you can do this. Here's how I usually declare enums so they don't collide:

enum EnumType {et1_val1 = -1, et1_val2 = 1};
enum EnumType2 {et2_val1 = 1, et2_val2 = -1};
John Dibling
A: 

I may be mistaken but I think the ambiguity in your example can be resolved with EnumType::val1 and EnumType2::val1

JoshD
I think that will work in C++0x, but not in C++98/C++03.
jamesdlin
I do this quite a bit at work. Unfortunately, I'm home now and can't check the exact version of gcc I'm using. I suspect it isn't standard according to c++98, so it's likely not very portable.
JoshD
A: 

You can have enums with arbitrary integer values, but you cannot have enum values with the same name. You have to either give them different names, or put them into different namespaces.

Dima
A: 

Yes, but val1 and val2 can't themselves be of integral type.

enum EnumType { et1_val1 = -1, et1_val2 = 1 };
enum EnumType2 { et2_val1 = 1, et2_val2 = -1 };

struct value_depends_on_conversion {
    EnumType enum1_value;
    EnumType2 enum2_value;

    operator EnumType() const
        { return enum1_value; }

    operator EnumType2() const
        { return enum2_value; }

} const val1 = { et1_val1, et2_val1 },
        val2 = { et1_val2, et2_val2 };

C++0x will improve this by allowing the conversions to be marked constexpr, so the global objects could be used as if they were really of the enum type.

Potatoswatter