gpt4 book ai didi

c++ - ADL 是否适用于全局 namespace ?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:09:58 24 4
gpt4 key购买 nike

Examples such as启用 std 的输出类型解释了如何 ADL可用于“注入(inject)”某个函数/运算符,具体取决于应用 fn/op 的类型。

我想知道 ADL 是否完全适用于全局命名空间,也就是说,是否在 global namespace scope 处声明(或通过 using 提供)类型让 ADL 在全局命名空间中寻找匹配的函数?

具体来说,这些是否等同于 wrt.日常事件能力?:

// 1 - at global namespace scope
struct GlobalType {};

template< class Ch, class Tr>
std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& os, GlobalType const& x)
{
os << ...;
return os;
}

// 2 - within namespace
namespace ecaps {

struct EcapsType {};

template< class Ch, class Tr>
std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& os, EcapsType const& x)
{
os << ...;
return os;
}

}

// 3 - Type brought to global NS via using, function at global scope
namespace other {
struct OtherType {};
}

using other::OtherType;

template< class Ch, class Tr>
std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& os, OtherType const& x)
{
os << ...;
return os;
}

写信。不需要 ADL 的全局命名空间范围:(在现在删除的答案后更新)

一个Daniel Krügler of Committee fame describes an ADL problem因此:

This unqualified call has the effect that unqualified name lookup happens and as a consequence of this, the compiler searches for the name operator<<. beginning from the lexical location where the operator<< call is found "upwards" (...) starting in the current namespace and all the namespaces that include that namespace (including the global namespace, btw.) and - ...

强调。矿。请注意如何将外部命名空间描述为仅被视为“... 来自词法位置 ...”。他继续说:

... and - as a second route - it performs a second phase of this lookup the compiler searches in the so-called associated namespaces of the argument types occurring in this call.

In the presented example, the first phase of the search fails, because at the point where #include <iterator> exists, there is no corresponding operator<< for these argument types in any namespace. Note that your declaration of operator<< is provided lexically after the point where the call of operator<< happens somewhere in some of the library headers. The second phase of the search would also consider locations that follow the actual function call, but only within the associated namespaces.

大胆强调。矿。所以在我看来,ADL 适用于全局 namespace 是相关的。当然,我很容易误解了一些东西。


注意:这可能是标准的一个例子,只是没有以这种或那种方式明确提及它,因为全局 NS 就像任何其他 namespace 一样——但我知道它也可能不是标准的内容非常有限。

最佳答案

完全忘记我最初的答案,那是完全错误的。

来自 C++11 标准,关于 ADL 的 §3.4.2(强调我的):

When the postfix-expression in a function call (5.2.2) is an unqualified-id, other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched, and in those namespaces, namespace-scope friend function declarations (11.3) not otherwise visible may be found.

简而言之,由于非限定查找将始终在全局命名空间中进行搜索,ADL 将永远应用于全局命名空间

关于c++ - ADL 是否适用于全局 namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25133383/

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