I'm trying to understand what kind of errors could arise from including using
declarations in namespaces. I'm taking into account these links.
I'm trying to create an example where an error is being caused by a name being silently replaced by an header file being loaded before another one, due to usage of the using
declaration.
Here I'm defining MyProject::vector
:
// base.h
#ifndef BASE_H
#define BASE_H
namespace MyProject
{
class vector {};
}
#endif
This is the "bad" header: here I'm trying to trick using
into shadowing other possible definitions of vector
inside MyNamespace
:
// x.h
#ifndef X_H
#define X_H
#include <vector>
namespace MyProject
{
// With this everything compiles with no error!
//using namespace std;
// With this compilation breaks!
using std::vector;
}
#endif
This is the unsuspecting header trying to use MyProject::vector
as defined in base.h
:
// z.h
#ifndef Z_H
#define Z_H
#include "base.h"
namespace MyProject
{
void useVector()
{
const vector v;
}
}
#endif
And finally here's the implementation file, including both x.h
and z.h
:
// main.cpp
// If I swap these two, program compiles!
#include "x.h"
#include "z.h"
int main()
{
MyProject::useVector();
}
If I include using std::vector
in x.h
, an actual compilation error happens, telling me that I must specify a template argument when using vector
in z.h
, because x.h
successfully managed to shadow the definition of vector
inside MyProject
. Is this a good example of why using
declarations shouldn't be used in header files, or things go deeper that this, and I'm missing much more?
If I include using namespace std
in x.h
, however, the shadowing doesn't occur, and the program compiles just fine. Why is that? Shouldn't using namespace std
load all names visible under std
, including vector
, thus shadowing the other one?