【问题标题】:Understanding the scope of operators in C++了解 C++ 中运算符的范围
【发布时间】:2013-06-09 16:43:19
【问题描述】:
#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();
}
我在Foo 命名空间中定义了一个operator<<。为什么可以从全局作用域调用?
【问题讨论】:
标签:
c++
function
namespaces
scope
argument-dependent-lookup
【解决方案1】:
DRTL
编译器可以通过argument-dependent lookup找到用户定义的operator<<。
说明
电话
std::cout << Foo::Baz();
实际上是
的中缀简写
operator<<(std::cout, Foo::Baz());
因为函数调用是不合格的(即没有任何命名空间前缀或周围的括号),编译器不仅会进行普通名称查找(从本地函数范围向外) ),还可以在参数std::cout 和类Baz 的所有关联命名空间 中查找函数operator<< 的其他重载的参数相关查找(又名ADL) .在这种情况下,这些关联的命名空间是 std 和 Foo。
因此,依赖于参数的查找将找到定义
std::operator<<(std::ostream&, /* all the builtin types and Standard strings and streams */)
Foo::operator<<(std::ostream&, const& Baz)
名称查找后,对于所有 std::operator<< 重载,参数推导将失败。这就是为什么重载解析会发现用户定义的Foo::operator<<实际上是唯一的匹配。这就是它被调用的原因。