Possible to wrap or merge separate namespaces?

前端 未结 3 644
遇见更好的自我
遇见更好的自我 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;
    }
    

提交回复
热议问题