このプログラムをコンパイルするとき、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]