Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import an enum into a different namespace in C++?

I have an enum in a namespace and I'd like to use it as if it were in a different namespace. Intuitively, I figured I could use 'using' or 'typedef' to accomplish this, but neither actually work. Code snippet to prove it, tested on GCC and Sun CC:

namespace foo {  enum bar {     A };  }  namespace buzz { // Which of these two methods I use doesn't matter, // the results are the same. using foo::bar; //typedef foo::bar bar; }  int main() {     foo::bar f; // works     foo::bar g = foo::A; // works      buzz::bar x; // works     //buzz::bar y = buzz::A; // doesn't work     buzz::bar z = foo::A; } 

The problem is that the enum itself is imported but none of its elements. Unfortunately, I can't change the original enum to be encased in an extra dummy namespace or class without breaking lots of other existing code. The best solution I can think of is to manually reproduce the enum:

namespace buzz { enum bar {     A = foo::A }; } 

But it violates the DRY principle. Is there a better way?

like image 776
Joseph Garvin Avatar asked Jul 20 '10 18:07

Joseph Garvin


People also ask

Can we have enum inside enum in C?

It is not possible to have enum of enums, but you could represent your data by having the type and cause separately either as part of a struct or allocating certain bits for each of the fields.

Can we change enum values in C?

You can change default values of enum elements during declaration (if necessary).

Can two enum names have the same value?

1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can we assign variable to enum?

A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong.


1 Answers

Wrap the existing namespace in a nested namespace which you then "use" in the original namespace.

namespace foo {     namespace bar_wrapper {         enum bar {             A         };     }     using namespace bar_wrapper; }  namespace buzz {     using namespace foo::bar_wrapper; } 
like image 62
Mark B Avatar answered Sep 27 '22 21:09

Mark B