Example of error caused by using directive in namespaces

帅比萌擦擦* 提交于 2019-12-11 06:54:24

问题


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?


回答1:


If I include using namespace std in x.h, however, the shadowing doesn't occur, and the program compiles just fine. Why is that?

This much I can answer from 7.3.4/2-3:

First

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive.

Then followed up:

A using-directive does not add any members to the declarative region in which it appears.

So a using-directive (using namespace) only makes the names usable from the target namespace, it does not make them members of it. So any existing member will be preferred over the used namespace member.



来源:https://stackoverflow.com/questions/39799873/example-of-error-caused-by-using-directive-in-namespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!