I\'m using the \'using\' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary \'std::\'s).
using std::str
The scope of the using statement depends on where it is located in the code:
There are a few comments that are rather unqualified when they say "Don't". That is too stern, but you have to understand when it is OK.
Writing using std::string
is never OK. Writing using ImplementationDetail::Foo
in your own header, when that header declares ImplementationDetail::Foo can be OK, moreso if the using declaration happens in your namespace. E.g.
namespace MyNS {
namespace ImplementationDetail {
int Foo;
}
using ImplementationDetail::Foo;
}
When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a using
declaration has the exact same effect of placing the using
declaration at the top of each file that includes that header file.
There's nothing special about header files that would keep the using
declaration out. It's a simple text substitution before the compilation even starts.
You can limit a using
declaration to a scope:
void myFunction()
{
using namespace std; // only applies to the function's scope
vector<int> myVector;
}
That is correct. The scope is the module that uses the using
declaration. If any header files that a module includes have using
declarations, the scope of those declarations will be that module, as well as any other modules that include the same headers.
The scope is whatever scope the using declaration is in.
If this is global scope, then it will be at global scope. If it is in global scope of a header file, then it will be in the global scope of every source file that includes the header.
So, the general advice is to avoid using declarations in global scope of header files.