[ Different enums, same value ]
Is it possible to make two different enums with a same value? For example,
enum direction{
LEFT,
RIGHT,
UP,
DOWN,
NONE
}
enum color{
RED,
GREEN,
BLUE,
NONE
}
The compiler would say that there are two declarations of 'NONE'. Is there a way around this?
Answer 1
There's a couple ways around this. One way is to use namespaces to wrap enums and prevent the values from polluting the global namespace:
namespace direction {
enum direction {
LEFT,
RIGHT,
UP,
DOWN,
NONE
};
}
namespace color {
enum color {
RED,
GREEN,
BLUE,
NONE
};
}
You can also use the new C++11 way (if your compiler supports it) and use "strongly-typed enums"
enum class direction {
LEFT,
RIGHT,
UP,
DOWN,
NONE
};
enum class color {
RED,
GREEN,
BLUE,
NONE
};
Both can be used by the syntax direction::NONE
or color::NONE
but there is one major difference. In the first case the enums will still implicitly cast to ints. This means you can write
int foo = direction::NONE;
and everything is fine.
In the second case, this would be a compiler error since foo is not the same type as direction. You can get around this by doing
direction foo = direction::NONE;
which may or may not work for you. If you need to cast it to an int, you are welcome to use static_cast<int>(foo)
to get an integer type.