[英]Understanding the scope of operators in C++
#include <iostream>
namespace Foo
{
class Baz { };
std::ostream& operator<< ( std::ostream& ostream , const Baz& baz )
{
return ostream << "operator<<\n";
}
}
int main()
{
std::cout << Foo::Baz();
}
I define an operator<<
in the Foo
namespace. 我在
Foo
命名空间中定义了一个operator<<
。 Why it can be called from the global scope? 为什么可以从全球范围调用它?
DRTL DRTL
The compiler can find the user-defined operator<<
through argument-dependent lookup . 编译器可以通过参数依赖查找找到用户定义的
operator<<
。
Explanation 说明
The call 电话
std::cout << Foo::Baz();
is actually an infix shorthand for 实际上是一个中缀速记
operator<<(std::cout, Foo::Baz());
Because the function call is unqualified (ie without any namespace prefix or surrounding parentheses), the compiler will not only do ordinary name lookup (outwards from the local function scope), but also argument-dependent lookup (aka ADL ) for other overloads of function operator<<
in all the associated namespaces of both arguments std::cout
and class Baz
. 因为函数调用是不合格的 (即没有任何名称空间前缀或周围的括号),编译器不仅会执行普通的名称查找 (从本地函数作用域向外),还会进行参数依赖查找(也称为ADL )以用于其他函数重载
operator<<
在两个参数std::cout
和class Baz
所有相关命名空间中。 These associated namespaces are std
and Foo
in this case. 在这种情况下,这些关联的命名空间是
std
和Foo
。
Thus argument-dependent lookup will find the definitions 因此,依赖于参数的查找将找到定义
std::operator<<(std::ostream&, /* all the builtin types and Standard strings and streams */)
Foo::operator<<(std::ostream&, const& Baz)
After name-lookup, argument deduction will fail for all the std::operator<<
overloads. 在名称查找之后,对于所有
std::operator<<
重载, 参数推断将失败。 This is why overload resolution will find that the user-defined Foo::operator<<
is in fact the only match. 这就是重载解析会发现用户定义的
Foo::operator<<
实际上是唯一匹配的原因。 That's why it is called. 这就是它被召唤的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.