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

前端 未结 5 1753
心在旅途
心在旅途 2020-12-11 14:20

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,

相关标签:
5条回答
  • 2020-12-11 14:56

    While i like the approach of Mark B best, because it doesn't break existing code, you can also do the following:

    namespace foo {
     enum bar {
      A, B [..]
     };
    }
    
    namespace buzz {
     using foo::bar;
     using foo::A;
     using foo::B;
     [..]
    }
    
    0 讨论(0)
  • 2020-12-11 15:00

    If you really need to do this, try using namespace foo; instead of using foo::bar;. However, it's a much better idea to encapsulate the enum in a class or in another namespace.

    0 讨论(0)
  • 2020-12-11 15:01

    Starting from C++11 you can use enum class. Importing enum class imports all its values:

    namespace foo
    {
    
    enum class bar {
        A
    };
    
    }
    
    namespace buzz
    {
    using foo::bar;
    }
    
    int main()
    {
        foo::bar f;
        foo::bar g = foo::bar::A;
    
        buzz::bar x;
        buzz::bar y = buzz::bar::A;
        buzz::bar z = foo::bar::A;
    }
    

    The code above successfully compiles: http://coliru.stacked-crooked.com/a/2119348acb75d270.

    0 讨论(0)
  • 2020-12-11 15:06

    The problem here is that the using declaration pulls in only the name of the enum, and not the names of its values. Enum's aren't scopes and don't carry along the names of the enumerators. I don't think it is possible to import the enum values themselves. Try wrapping the enum in a struct/namespace and use it.

    0 讨论(0)
  • 2020-12-11 15:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题