Why “using namespace X;” is not allowed inside class/struct level?

后端 未结 5 667
走了就别回头了
走了就别回头了 2020-11-27 15:35
class C {
  using namespace std;  // error
};
namespace N {
  using namespace std; // ok
}
int main () {
  using namespace std; // ok
}

Edi

5条回答
  •  时光说笑
    2020-11-27 16:10

    I think it's a defect of the language. You may use workaround below. Keeping in mind this workaround, it is easy to suggest rules of names conflicts resolution for the case when the language will be changed.

    namespace Hello
    {
        typedef int World;
    }
    // surround the class (where we want to use namespace Hello)
    // by auxiliary namespace (but don't use anonymous namespaces in h-files)
    namespace Blah_namesp {
    using namespace Hello;
    
    class Blah
    {
    public:
        World DoSomething1();
        World DoSomething2();
        World DoSomething3();
    };
    
    World Blah::DoSomething1()
    {
    }
    
    } // namespace Blah_namesp
    
    // "extract" class from auxiliary namespace
    using Blah_namesp::Blah;
    
    Hello::World Blah::DoSomething2()
    {
    }
    auto Blah::DoSomething3() -> World
    {
    }
    

提交回复
热议问题