c++ - 为什么 `using A::f` 没有按预期工作?

标签 c++ namespaces using

以下代码被 VC++ 和 clang 拒绝。

为什么 using A::f 没有按预期工作?

有没有办法在给定的命名空间中隐藏一些名字?

namespace A
{
    int f()
    {
        return 1;
    }
};

namespace B
{
    int f()
    {
        return 2;
    }
};

using namespace A;
using namespace B;

using A::f; // I want to hide B::f and only use A::f, how to do?

int main()
{
    auto n = f(); // error : call to 'f' is ambiguous
}

最佳答案

该标准指定了using 指令的解释。强调我的:

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 ]

(C++11 §7.3.4/2)

因此,之后

using namespace A;
using namespace B;

对名称 f 的非限定查找找到 A::fB::f 就好像它们已被声明一样在全局命名空间中。声明 using A::f 以相同的方式将名称 f 引入全局命名空间(尽管不同之处在于它实际上使 A::f 全局命名空间的成员),因此就非限定查找而言,它是多余的。重点是 f 的非限定名称查找在同一声明区域中找到 A::fB::f

解决方案?

int main()
{
    using A::f;
    auto n = f(); // no longer ambiguous; finds A::f
}

非限定名称查找首先查找的是 main 的 block 作用域,因此它只会找到 A::f,即使 A:如果搜索,:fB::f 都会在封闭的命名空间范围内找到。

关于c++ - 为什么 `using A::f` 没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319602/

相关文章:

c++ - 为什么我在使用 nullptr_t 时收到 "parameter set but not used"警告?

c# - 防止 Visual Studio 在复制粘贴时自动导入命名空间

sql - MySQL/SQL 的简写 "Using"可以不说 "Inner Join"就用吗?

javascript - 使用 javascript 获取复选框状态

c++ - 如何更改进程可以分配的最大内存(每次大约 2040 MB 时都会出现访问冲突)

c++ - std::function 与 std::bind 配合得很好——但为什么呢?

clojure - 为什么 Clojure 在创建新的命名空间后不提供标准库?

xml - Actionscript 3 E4X 使用 XML 中的命名空间值

c++ - 如何为枚举类编写 'using' 语句?

c++ - 在 C++ 中查找 C 风格 char * 字符串的长度