1

How can I force all enums to have their own namespace?

I have multiple enums with members that have the same name, and want them to be accessed through the enum namespace,

for example

enum X {b, a};
enum Y {a, b};

The above code won't compile because a is either X::a or Y::a

How can I make it so that a can never be used unless the client specifies X::A or Y::A, so it compiles?

Jason
  • 1,287
  • 11
  • 23

2 Answers2

2

One solution is to actually use real namespaces for this:

#include <iostream>

namespace X { enum X {b = 1, a = 2}; }
namespace Y { enum Y {a = 3, b = 4}; }

int main (void) {
    std::cout << X::a << std::endl;          // use value.
    std::cout << sizeof(Y::Y) << std::endl;  // use type.
    Y::Y yy = Y::b;                          // set variable.

    return 0;
}

You can see three likely operations (using the values directly, using the type, and declaring/setting variables) in the respective lines of main().

paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899
2
enum class X {b, a};
enum class Y {a, b};

this does what you want, and also disables a bunch of implicit conversion to integral types that enums do.

Yakk - Adam Nevraumont
  • 250,370
  • 26
  • 305
  • 497