【发布时间】:2015-09-28 03:14:39
【问题描述】:
以下代码位于两个源文件中。
第一:
namespace A {
// two friends; neither is declared apart from a friend declaration
// these functions implicitly are members of namespace A
class C {
friend void f2(); // won’t be found, unless otherwise declared
friend void f1(const C&); // found by argument-dependent lookup
};
}
int main()
{
A::C obj;
f1(obj); // ok: find A::f through the friend declaration in A::C
A::f2(); // no member named f2 in namespace A
}
第二个:
#include <iostream>
namespace A {
class C;
void f1(const C&) {
std::cout << 1;
}
void f2() {
std::cout << 2;
}
}
第一段代码是从 C++ Primer 复制而来,唯一的区别是 C++ Primer 调用 f2() 没有前缀命名空间。第二件是我的补充。我现在想知道 f1 和 f2 隐含地是命名空间 A 的成员,为什么 A::f2() 仍然错误而 f1(obj) 可以被 ADL 找到吗?
【问题讨论】:
-
我第一次遇到 ADL……我的反应大概是“OHMYGODWHY”。
-
@Cubic 以便
std::cout << 'x';工作。如果没有 ADL,您将不得不编写using std::operator<<或std::operator<<(std::cout, 'x');等。
标签: c++ friend-function