c++ namespace best practice dilemma

后端 未结 6 2044
遥遥无期
遥遥无期 2021-01-31 03:55

I\'m finding that what I\'ve considered \"best practice\" for use namespace in c++ is hurting the readability of my code, and making me question how to use them well.

My

6条回答
  •  感情败类
    2021-01-31 04:34

    I use the following to get rid of enormous amounts of std:: in header file:

    // mylibrary.h
    namespace myproject {
      namespace mylibrary {
        namespace impl {
    
          using namespace std;
    
          namespace stripped_std {
    
            // Here goes normal structure of your program:
            // classes, nested namespaces etc.
            class myclass;
            namespace my_inner_namespace {
                    ...     
            }
    
           } // namespace stripped_std   
        } // namespace impl
    
      using namespace impl::stripped_std;
    
      } // namespace mylibrary
    } namespace myproject
    
    
    // Usage in .cpp file
    #include 
    using namespace myproject::mylibrary;
    

    It is similar to what was suggested by n.m., but with a modification: there is one more auxiliary namespace stripped_std. The overall effect is that line using namespace myproject::mylibrary; allows you to refer to the inner namespace structure, and at the same time it does not bring namespace std into library user's scope.


    It's a pity though that the following syntax

    using namespace std {
    ...
    }
    

    is not valid in C++ at the time when this post is written.

提交回复
热议问题