king_nak
king_nak

Reputation: 11513

Accessing enum values from other class

In my project, I have an enum defined in a class, that is used throughout that class. During refactoring, that enum was moved to another class. So I simply typedefed it in my original class, like this:

class A {
public:
  enum E {e1, e2};
};
class B {
public:
  typedef A::E E;
};

Now variable definitions, return values, function params, etc. work perfectly. Only when I want to access the values of the enum inside my second class, I still have to qualify them with the surroundig class's name,
e.g. E e = A::e1;

Is there a way to avoid this, or do I have to copy that into every occurance of the enum values?

Upvotes: 5

Views: 3707

Answers (2)

arne
arne

Reputation: 4674

If you're not above using c++11, you could have a look at enum classes.

Upvotes: 0

Mark B
Mark B

Reputation: 96243

You put each enumeration into a nested class that you can typedef within your own class:

class A {
public:
  struct E { enum EnumType { e1, e2 } };
};
class B {
public:
  typedef A::E E;
};

Then it's just E::EnumType instead of E but you get full auto-importation.

Upvotes: 2

Related Questions