Is there a better way to express nested namespaces in C++ within the header

前端 未结 11 2468
天涯浪人
天涯浪人 2020-12-13 03:31

I switched from C++ to Java and C# and think the usage of namespaces/packages is much better there (well structured). Then I came back to C++ and tried to use namespaces the

11条回答
  •  醉酒成梦
    2020-12-13 03:40

    This paper covers the subject rather well: Namespace Paper

    Which basically boils down this. The longer your namespaces are the more likely the chance that people are going to use the using namespace directive.

    So looking at the following code you can see an example where this will hurt you:

    namespace abc { namespace testing {
        class myClass {};
    }}
    
    namespace def { namespace testing {
        class defClass { };
    }}
    
    using namespace abc;
    //using namespace def;
    
    int main(int, char**) {
        testing::myClass classInit{};
    }
    

    This code will compile fine, however, if you uncomment the line //using namespace def; then the "testing" namespace will become ambiguous and you will have naming collisions. This means that your code base can go from stable to unstable by including a 3rd party library.

    In C#, even if you were to use using abc; and using def; the compiler is able to recognize that testing::myClass or even just myClass is only in the abc::testing namespace, but C++ will not recognize this and it is detected as a collision.

提交回复
热议问题