views:

234

answers:

5

Suppose you have a class with an enum defined within it:

class MyClass {
  typedef enum _MyEnum{ a } MyEnum;
}

Is there a way to access the value a from another class without having to refer to it as MyClass::a? If the enum were contained within a namespace rather than a class, than "using namespace ;" solves the problem - is there an equivalent way to do this with classes?

+4  A: 

I'm pretty sure you're stuck with "MyClass::a". Also... wouldn't doing this kind of defeat the purpose of putting the enum inside a class in the first place?

Russell Newquist
Depend where the using is used. It can be used locally, ex in a function: void func(){using MyClass::a;}. This wouldn't make it accessible by refering to 'a' outside of the function. So no I don't think it would defeat the purpose.
n1ck
+3  A: 

The best you can do is pull individual symbols into the class.

class SomeClass {
    typedef MyClass::MyEnum MyEnum;
    MyEnum value;
};

Note that if the typedef is in a public section of the class then anyone can refer to SomeClass::MyEnum as a synonym of MyClass::MyEnum.

Tim Sylvester
A: 

Unless that another class is a derived class of MyClass (and your enum is protected/public), no. I know this is not an answer but in my opinion the enum is defined inside MyClass for a reason, so don't try to make it globally available.

Murali VP
A: 

An alternative would be to publically derive from an Enum-holder-class:

struct Holder {
    enum MyEnum { a };
};

class User : public Holder {
public:
    // a now visible in class
    MyEnum f() { return a; } 
};

// a visible outside too
User::MyEnum f() { return User::a; }
Georg Fritzsche
A: 

You can pull in each constant individually as follows:

class MyClass {
  public:
  // I added a value here intentionally to show you what to do with more than one enum value
  typedef enum _MyEnum{ a, b } MyEnum;
}
using MyClass::a;
using MyClass::b;
//... likewise for other values of the enum
Ken Bloom