Jmoney38
Jmoney38

Reputation: 3294

C++ Namespace 'using' declarative for a class' enum

I have a good understanding of how the C++ 'using' declaration and directive work. However, I'm stumped on this... Maybe it's not possible? I want to avoid having to quality my enum variables:

namespace Foo { 
   class MyClass {
      public: 
         enum MyEnum { X, Y, Z };
   }
}

And now, from outside that namespace, I would like to be able to do things like:

using Foo::MyClass.MyEnum;
MyEnum letter = MyEnum::x;

But apparently that's not the way to do it? I'm betting this is possible, but my notation is wrong... I also tried using Foo::MyClass::MyEnum, but then the compiler thinks Foo::MyClass is a namespace.

Added: As you can see, it becomes annoying having to fully declare everything...

Foo::MyClass::MyEnum value = Foo::MyClass::X;

Upvotes: 10

Views: 4394

Answers (3)

ptpaterson
ptpaterson

Reputation: 9583

I got the following to compile, after messing around a lot. I think that it will be the closest you can get without typedef'ing.

namespace Foo {
    class MyClass {
        public:
            enum MyEnum { X, Y, Z };
    };
};

namespace Foo2 {
    using Foo::MyClass; 

    class AnotherClass {
        public:

            AnotherClass(){
                MyClass::MyEnum value = MyClass::X; 
            }
    };
};

int main(){

    return 1;
}

You could also use MyClass as a base class, but I am doubting that's something you want to do.

namespace Foo2 {
    using namespace Foo;
    class AnotherClass : public MyClass{
        public:
            AnotherClass(){
                MyEnum value = X; 
            }
    };
};

This also has some good info. namespaces for enum types - best practices

Upvotes: 1

Puppy
Puppy

Reputation: 146910

C++03 does not support fully qualifying enum types, but it's an MSVC extension. C++0x will make this Standard, and I believe that you can using an enum in C++0x. However, in C++03, I don't believe that your problem can be solved.

Upvotes: 1

Chris Frederick
Chris Frederick

Reputation: 5584

This doesn't answer your question directly, but if you want to economize keystrokes you could try using a typedef instead.

typedef Foo::MyClass::MyEnum MyClassEnum;

By the way, it looks like your question has been asked on Stack Overflow before. From the answer to that question:

A class does not define a namespace, therefore "using" isn't applicable here.

Upvotes: 6

Related Questions