[英]When is ADL applied?
有3个例子:
一世。
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
}
二、
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
}
三、
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
}
我不清楚 ADL 查找的实际条件是什么? 我需要参考标准来描述它。
这个标准段落澄清了,甚至有一个非常像你的第一个例子的例子。
3.4.1/3:
在 3.4.2 [basic.lookup.argdep] 中描述了对用作函数调用后缀表达式的非限定名称的查找。 [注意:为了确定(在解析期间)表达式是否是函数调用的后缀表达式,通常的名称查找规则适用。 3.4.2 中的规则对表达式的句法解释没有影响。 例如,
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)
}
};
}
由于该表达式不是函数调用,因此参数相关名称查找 (3.4.2) 不适用并且未找到友元函数
f
。 -尾注]
你的第一个例子没有说明 ADL。 在行中
int t=foo(B::S());
foo
是typedef
ed 到int
。
以下代码对 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.