Limiting the scope of "using namespace" in a header file

c++, namespaces, scope

Solution

Yes, I think that can be done.

In order to achieve that you need to build your own namespace. I have written some code which is working as per the expected.

Header file looks like:

#include <iostream>
namespace my_space {
    using namespace std;

    void mprint ()
    {
        /*
         * This is working. It means we can access
         * std namespace inside my_space.
        */
        cout << "AAA" << endl; 
    }
};

Implementation file looks like:

#include "my_header.h"

int main ()
{

    /*
     * Working Fine.
    */
    my_space::mprint();

    /*
     * It gives a compile time error because
     * it can't access the std namespace
    */
    cout << "CHECK" << endl;
    return 0;
}

Please let me know if this does not satisfy your requirement. We can work out on that.

Problem

I'm working on a small personal C++ project using STL. I don't like having "`std::`" all over the place in my header files, as I find it hinders readability, but at the same time I don't want to cause myself problems later on by putting `using namespace std` in a header file. So I'm wondering if there's a way to limit the scope of the `using` declaration, so that it applies to the contents of my header file, but doesn't apply to files that include it. I tried various things like this ``` { using namespace std; // header file contents here } ``` but it seems that introducing a scope this way is not allowed outside of a function definition. Is there a way to do what I'm after? Please note: I'm really not interested in discussing whether this is a good idea, I just want to know if it can be done.

Original source