Possible to wrap or merge separate namespaces?

前端 未结 3 645
遇见更好的自我
遇见更好的自我 2021-01-18 09:55

I seem to recall seeing notes somewhere on a way to combine multiple namespaces into one.

Now, looking for said notes I am not finding them -- even searching using s

相关标签:
3条回答
  • 2021-01-18 10:14

    The best solution since C++11 is:

    namespace c
    {
        inline namespace a { using namespace ::a; }
        inline namespace b { using namespace ::b; }
    }
    

    This way for names that not conflict you can qualify only by c and you can resolve conflicts by qualifing c::a or c::b.

    e.g.:

    namespace a
    {
        auto foo_a() { cout << "a::foo_a" << endl; }
        auto foo() { cout << "a::foo" << endl; }
    }
    namespace b
    {
        auto foo_b() { cout << "b::foo_b" << endl; }
        auto foo() { cout << "b::foo" << endl; }
    }
    
    namespace c
    {
        inline namespace a { using namespace ::a; }
        inline namespace b { using namespace ::b; }
    }
    
    int main()
    {
      c::foo_a();
      c::foo_b();
    
      c::a::foo();
      c::b::foo();
    
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-18 10:30

    You can wrap the namespaces in a new one like this:

    namespace c {
        namespace a { using namespace ::a; }
        namespace b { using namespace ::b; }
    }
    
    0 讨论(0)
  • 2021-01-18 10:36

    You can do this:

    namespace c
    {
        using namespace a;
        using namespace b;
    }
    

    But if a and b have elements with the same names, you won't be able to use them from namespace c.

    0 讨论(0)
提交回复
热议问题