Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

namespaces

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;
like image 989
Jmoney38 Avatar asked Jun 09 '11 19:06

Jmoney38


People also ask

What are is difference between using namespace directive and using the using declaration for accessing namespace members?

Use a using directive in an implementation file (i.e. *. cpp) if you are using several different identifiers in a namespace; if you are just using one or two identifiers, then consider a using declaration to only bring those identifiers into scope and not all the identifiers in the namespace.

Does C support namespace?

No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.

What is the need of using namespace in a class?

Namespace in C++ is the declarative part where the scope of identifiers like functions, the name of types, classes, variables, etc., are declared. The code generally has multiple libraries, and the namespace helps in avoiding the ambiguity that may occur when two identifiers have the same name.

What is global namespace in C++?

Beginning of C++ only. Global scope or global namespace scope is the outermost namespace scope of a program, in which objects, functions, types and templates can be defined. A name has global namespace scope if the identifier's declaration appears outside of all blocks, namespaces, and classes.


2 Answers

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.

like image 167
Chris Frederick Avatar answered Sep 22 '22 13:09

Chris Frederick


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.

like image 39
Puppy Avatar answered Sep 22 '22 13:09

Puppy