[英]When is ADL applied?
There are 3 examples:有3个例子:
I.一世。
typedef int foo;
namespace B
{
struct S
{
operator int(){ return 24; }
};
int foo(B::S s){ return 0; }
}
int main()
{
int t=foo(B::S()); //24, ADL does not apply
}
II.二、
namespace B
{
struct S
{
operator int(){ return 24; }
};
int foo(B::S s){ return 0; }
}
int main()
{
int t=foo(B::S()); //0, ADL applies
}
III.三、
namespace B
{
struct S
{
operator int(){ return 24; }
};
int foo(B::S s){ return 0; }
}
int foo(B::S s){ return 12; }
int main()
{
int t=foo(B::S()); //error: call of overloaded ‘foo(B::S)’ is ambiguous
//ADL applies
}
It is not clear for me what is the actual conditions to ADL lookup will be apply?我不清楚 ADL 查找的实际条件是什么? I need in reference to standard described it.我需要参考标准来描述它。
This Standard paragraph clarifies, and even has an example very much like your first example.这个标准段落澄清了,甚至有一个非常像你的第一个例子的例子。
3.4.1/3: 3.4.1/3:
The lookup for an unqualified name used as the postfix-expression of a function call is described in 3.4.2 [basic.lookup.argdep].在 3.4.2 [basic.lookup.argdep] 中描述了对用作函数调用后缀表达式的非限定名称的查找。 [ Note: For purposes of determining (during parsing) whether an expression is a postfix-expression for a function call, the usual name lookup rules apply. [注意:为了确定(在解析期间)表达式是否是函数调用的后缀表达式,通常的名称查找规则适用。 The rules in 3.4.2 have no effect on the syntactic interpretation of an expression. 3.4.2 中的规则对表达式的句法解释没有影响。 For example,例如,
typedef int f;
namespace N {
struct A {
friend void f(A &);
operator int();
void g(A a) {
int i = f(a); // f is the typedef, not the friend
// function: equivalent to int(a)
}
};
}
Because the expression is not a function call, the argument-dependent name lookup (3.4.2) does not apply and the friend function
f
is not found.由于该表达式不是函数调用,因此参数相关名称查找 (3.4.2) 不适用并且未找到友元函数f
。 - end note ] -尾注]
Your first example does not illustrate ADL.你的第一个例子没有说明 ADL。 In the line在行中
int t=foo(B::S());
foo
is typedef
ed to int
. foo
是typedef
ed 到int
。
The following code has some better illustrations of ADL.以下代码对 ADL 有一些更好的说明。
#include <iostream>
namespace B
{
struct S
{
operator int(){ return 24; }
};
int foo(S s){ return 100; }
int bar(S s){ return 400; }
}
namespace C
{
struct S
{
operator int(){ return 24; }
};
int foo(S s){ return 200; }
}
int bar(C::S s){ return 800; }
int main()
{
// ADL makes it possible for foo to be resolved to B::foo
std::cout << foo(B::S()) << std::endl;
// ADL makes it possible for foo to be resolved to C::foo
std::cout << foo(C::S()) << std::endl;
// ADL makes it possible for bar to be resolved to B::bar
std::cout << bar(B::S()) << std::endl;
// ADL makes it possible for bar to be resolved to ::bar
std::cout << bar(C::S()) << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.