gpt4 book ai didi

c++ - 为什么 using 指令不影响 ADL?

转载 作者:太空狗 更新时间:2023-10-29 20:39:34 25 4
gpt4 key购买 nike

我试图理解为什么以下代码无法编译:

namespace ns {
struct S {};
}

namespace alleq {
inline bool
operator==(const ns::S &, const ns::S &)
{
return true;
}
}

namespace ns {
using namespace alleq;
// using alleq::operator==; // Works if you uncomment this
}

ns::S a;

void
f()
{
::ns::operator==(a, a); // OK
a == a; // Error: no match for 'operator=='
}

函数 f 的第一行编译,这让我相信命名空间 ns 包含一个函数 operator==。但是,当我比较 ns::S 类型的两个值时,找不到此 operator== 函数。相比之下,using 声明确实按预期工作,并允许 f 的第二行通过 ADL 查找 ns::operator==

我怀疑原因与这样一个事实有关,即 using 指令 应该使符号看起来好像在全局命名空间 :: 中(因为这是命名空间 alleqns 的共同祖先)。但如果真是这样,那为什么 ::ns::operator== 会找到这个函数?

更一般地说,我试图在库中提供一些有用的operator==(和相关的)重载,但如果人们不想要它们,我不会强制他们使用这些定义。我希望允许人们根据他们是否将专用运算符 namespace 导入到他们自己的 namespace 中来启用或不启用他们的类型的运算符==(和相关的其他运算符)。现在看来人们可能不得不编写大量的 using 声明(我可以用宏来简化,但是讨厌)。

最佳答案

I suspect the reason has to do with the fact that a using directive is supposed to make the symbol appear as if it is in the global namespace :: (because that is the common ancestor of namespaces alleq and ns).

这有点对,但仅适用于非限定查找,不适用于依赖于参数的查找:

7.3.4 [命名空间.udir]:

  1. 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.

由于这仅适用于非限定名称查找,因此只有在从封闭 namespace 内执行名称查找时,当名称查找“向外”查找封闭 namespace 时,它才真正有帮助。它无助于从 namespace 外部查找非限定名称(ADL 就是这样做的)。

下一段指出:

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

即using 指令使名称在范围内可见,但不会向范围添加新声明。

您看到的行为的原因很简单,标准说 ADL 忽略了 using 指令:

3.4.2 [basic.lookup.argdep]

  1. When considering an associated namespace, the lookup is the same as the lookup performed when the associated namespace is used as a qualifier (3.4.3.2) except that:
    — Any using-directives in the associated namespace are ignored.

关于c++ - 为什么 using 指令不影响 ADL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27544893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com