gpt4 book ai didi

c++ - 我需要对 Stroustrup 关于 ADL 的新书上的这个例子做一些澄清

转载 作者:太空狗 更新时间:2023-10-29 21:01:12 26 4
gpt4 key购买 nike

我在下面重现了 Stroustrup 书(第 4 版)第 396 和 397 页中给出的参数相关查找 (ADL) 示例:

namespace N {
struct S { int i; };
void f(S);
void g(S);
void h(int);
};

struct Base {
void f(N::S);
};

struct D : Base {
void mf(N::S);

void g(N::S x)
{
f(x); // call Base::f()
mf(x); // call D::mf()
h(1); // error: no h(int) available
}
};

上面的评论是正确的(我已经测试过了),但这似乎与作者在下一段中所说的不一致:

In the standard, the rules for argument-dependent lookup are phrased in terms of associated namespaces (iso §3.4.2). Basically:

  • If an argument is a class member , the associated namespaces are the class itself (including its base classes) and the class's enclosing namespaces.
  • If an argument is a member of a namespace, the associated namespaces are the enclosing namespaces.
  • If an argument is a built-in type, there are no associated namespaces.

在示例中,类型为N::Sx 不是D 类的成员,也不是其基类基础。但它是 namespace N 的成员。根据上面的第二个项目符号,函数 N::f(S) 应该被调用,而不是 Base::f()

上面的结果似乎也不符合标准中第 3.4.2p2 段中的第二个项目符号,它说:

If T is a class type (including unions), its associated classes are: the class itself; the class of which it is a member, if any; and its direct and indirect base classes. Its associated namespaces are the namespaces of which its associated classes are members. Furthermore, if T is a class template specialization, its associated namespaces and classes also include: the namespaces and classes associated with the types of the template arguments provided for template type parameters (excluding template template parameters); the namespaces of which any template template arguments are members; and the classes of which any member templates used as template template arguments are members.

最佳答案

3.4.2/3 Let X be the lookup set produced by unqualified lookup (3.4.1) and let Y be the lookup set produced by argument dependent lookup (defined as follows). If X contains

  • a declaration of a class member, or
  • a block-scope function declaration that is not a using-declaration, or
  • a declaration that is neither a function or a function template

then Y is empty. Otherwise...

所以基本上,当普通查找找到成员函数或局部( block 作用域)函数声明(或不是函数的东西)时,ADL 不会启动。当普通查找找到一个独立的命名空间作用域函数时,或者当它什么也没找到时,它确实会启动。

关于c++ - 我需要对 Stroustrup 关于 ADL 的新书上的这个例子做一些澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209453/

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