在编译这个程序时,我期望 operator<< 调用解析为全局命名空间中的那个,但是编译器却报告了一个模棱两可的重载。我认为非依赖查找发生在命名空间中的函数之前,这些函数由于参数依赖查找而被包含为潜在匹配项。这似乎是非模板函数的情况。
有人可以解释吗?
#include <iostream>
class Foo
{};
namespace NS
{
class Stream
{};
template <typename T>
Stream& operator << ( Stream& s, T t)
{
std::cerr << "Namespace call!\n";
return s;
}
}
template<typename STREAM>
STREAM& operator << ( STREAM& s, Foo f )
{
std::cerr << "Global NS call";
return s;
}
/**
* This function (as opposed to the one above) is not ambiguous. Why?
NS::Stream& operator << ( NS::Stream& s, Foo f )
{
std::cerr << "Global NS call";
return s;
}
*/
int main()
{
Foo f;
NS::Stream s;
s << f;
return 0;
}
编译器输出:
test11.cpp: In function ‘int main()’:
test11.cpp:28: error: ambiguous overload for ‘operator<<’ in ‘s << f’
test11.cpp:18: note: candidates are: STREAM& operator<<(STREAM&, Foo) [with STREAM = NS::Stream]
test11.cpp:13: note: NS::Stream& NS::operator<<(NS::Stream&, T) [with T = Foo]