I would do something similar to Lut_99 (but slightly different):
namespace choice_ns {
enum Choice { rock, paper, scissors };
}
using choice_ns::Choice;
bool beats(Choice a, Choice b) {
using namespace choice_ns;
switch (a) {
case rock:
// etc...
}
void does_not_compile() {
rock; // This requires qualification.
}
Notice that enum class
is not used, but a similar effect is achieved: you MUST use the choice_ns::
prefix when saying rock
. This avoids polluting the outer namespace, which is the main point of enum class
. Also notice that, like enum class
, you can refer to Choice
WITHOUT the choice_ns::
prefix.
The name of the namespace is deliberately awkward, because the only time you need it is when you say using namespace ...
at the beginning of your functions.
One difference between this and what Lut_99 suggests is that if you do it his way, declarations look like this:
choice::type a;
which is both verbose and awkward compared to my way:
Choice a;
Some of the other suggestions involve doing
constexpr SomeType rock = whatever::rock;
But this is really not great, because repetition, which means there's a good chance that you will make a mistake, especially if you decide to add values later on. E.g. https://www.youtube.com/watch?v=Kov2G0GouBw
I have been wanting this for a while. Good to see from Baptistou that this is going to be possible in the not too distant future. In the mean time, you can get something very similar using technology that's currently available today.