c++ - 使用指令的行为

标签 c++

我对 using-directive 感到困惑。

根据 C++11 标准 §7.3.4 p.3,

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

此外,C++11 标准 §7.3.4 不处理限定名称查找。

因此,恕我直言,using-directive 对限定名称查找没有影响。
例如,我认为下面的示例代码应该会导致编译错误。

#include <iostream>

namespace A {
    namespace B {
        int i = 1;
    }
    using namespace B;
}

int main()
{
    std::cout << A::i << std::endl;
}

但是 gcc 和 clang 都成功编译了这段代码。 ( http://melpon.org/wandbox/permlink/rXPjE5k12yMtlvMg )

此外,C++11 标准 §7.3.1.1 说未命名命名空间定义的行为就好像它被替换为

inlineopt namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }

and shows following example (the unnecessary part were omitted).

namespace { int i; }    // unique::i

namespace A {
    namespace {
        int i;          // A::unique::i
    }
}

using namespace A;
void h() {
    i++;                // error: unique::i or A::unique::i
    A::i++;             // A::unique::i
}

这个例子说明 h 函数的 A::i 可以引用未命名的命名空间成员 i

救救我,我再也看不懂了。

你能教我 using-directive 的正确解释吗?

最佳答案

有7.3.4

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. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace. [ Note: In this context, “contains” means “contains directly or indirectly”. — end note ]

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

上面的解释是 using-directive 将名称拉入范围,而不是声明( namespace 成员), 本身。

这可能说明了这一点:

namespace N {
    template <typename T> void f() {};
}

using namespace N;

// error: specialization of ‘template<class T> void N::f()’ in different
//        namespace
template <> void f<int>() {};

在第二个例子中有两个未命名的命名空间:

应用一些小的改变:

#include <iostream>

namespace { int i = 0; }    // unique::i

namespace A {
    namespace {
        int i = 1;          // A::unique::i
    }
}

using namespace A;

int main () {
    // i++; // error: unique::i or A::unique::i
    // The i having the value 1:
    std::cout << A::i << std::endl; // A::unique::i
    return 0;
}

关于c++ - 使用指令的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20853784/

相关文章:

c++ - 逐行读取文本文件会使 vector 为空

java - 如何设置诺基亚应用程序开发环境?

c++ - 包含 sdl/sdl.h 需要哪个库

c++ - 类成员函数地址

c++ - 在 C++ 中添加 const-ness

c++ - 如何将非静态成员函数用于模板参数?

C++在同一行读取具有多种类型的文件

c++ - 在画家程序中实现撤消重做

c++ - 分层数据模型的替代方案

c++ - 简单的程序,无法执行 for 循环