以下代码被 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::f
和 B::f
就好像它们已被声明一样在全局命名空间中。声明 using A::f
以相同的方式将名称 f
引入全局命名空间(尽管不同之处在于它实际上使 A::f
全局命名空间的成员),因此就非限定查找而言,它是多余的。重点是 f
的非限定名称查找在同一声明区域中找到 A::f
和 B::f
。
解决方案?
int main()
{
using A::f;
auto n = f(); // no longer ambiguous; finds A::f
}
非限定名称查找首先查找的是 main
的 block 作用域,因此它只会找到 A::f
,即使 A:如果搜索,:f
和 B::f
都会在封闭的命名空间范围内找到。
关于c++ - 为什么 `using A::f` 没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319602/