Reputation: 8439
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.
Upvotes: 11
Views: 5714
Reputation: 16737
No, it cannot be done. Your attempt to introduce a scope in the header failed exactly because there is no such thing as a header scope - header files do not have a special status during compilation. The translation units are source file obtained after the preprocessor is done with it. Thus, all the include
directives simply expand the corresponding header files. This prevents you from making the contents of the header file context-specific in any way.
Upvotes: 3
Reputation: 366
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.
Upvotes: 6