gpt4 book ai didi

具有模板函数的嵌套命名空间中的 C++ ADL

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:32:39 25 4
gpt4 key购买 nike

我对 C++ 中的标准 ADL 解析有疑问。

这是解释我的查询的示例代码:

#include <string>

// The mechanism:
namespace A {

template< class C >
::std::string scope(const C*)
{ return "A"; }

namespace B {

template< class C >
::std::string scope(const C *foo)
{ return A::scope(foo)+"::B"; }

} // namespace B
} // namespace A

::std::string scope(...)
{ return ""; }

// The test classes
struct foo {};
namespace A {
struct foo {};
namespace B {
struct foo {};
}
}

// The usage
int main()
{
foo *Foo=0;
A::foo *FooA=0;
A::B::foo *FooB=0;

scope(Foo); // OK, returns ""
scope(FooA); // OK, returns "A"
scope(FooB); // On one compiler, OK returns "A::B" ; On another, compiler error "Ambiguous call" between A::scope() and A::B::scope()
}

那么,我的问题是关于 ADL 的标准是什么?是应该找到参数的父 namespace 中的所有函数,还是只找到参数的(嵌套) namespace 中可用的函数 + 全局函数?

此程序已在 MSVC 2008 上测试(并使用 SP 编译,但并非没有...)

最佳答案

根据标准,ADL 有效(模数一些特殊规则)“好像”函数名前面有命名空间;在你的最后行,查找应该在前面,就像您编写了 A::B::scope 一样。哪个不查看周围的命名空间。

请注意,即使在命名空间 A::B 中,也不会有歧义;在A::BA::B::scope 隐藏了 A::scope。不合格的名称查找停止在它首先找到名称的范围内。

关于具有模板函数的嵌套命名空间中的 C++ ADL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5975736/

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