Search code examples
c++using-directives

Restricting `using` directives to the current file


Sorry for this silly question, but is there any way to restrict using directives to the current file so that they don't propagate to the files that #include this file?


Solution

  • Perhaps wrapping the code to be included inside its own namespace could achieve the behavior
    you want, since name spaces have scope affect.

    // FILENAME is the file to be included
    namespace FILENAME_NS {
       using namespace std;
       namespace INNER_NS {
          [wrapped code]
       }
    }
    using namespace FILENAME_NS::INNER_NS;
    

    and in some other file

    #include <FILENAME>
    // std namespace is not visible, only INNER_NS definitions and declarations
    ...