stl copy() を使用してキーと値のペアをマップに出力しようとしています。コードは次のとおりです。
#include <iterator>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
//compile error if I comment out "namespace std"
namespace std {
template<typename F, typename S>
ostream& operator<<(ostream& os, const pair<F,S>& p) {
return os << p.first << "\t" << p.second << endl;
}
}
int main() {
map<int, int> m;
fill_n(inserter(m, m.begin()), 10, make_pair(90,120));
copy(m.begin(), m.end(), ostream_iterator<pair<int,int> >(cout,"\n"));
}
operator<< をオーバーロードしようとしています。問題は、オーバーロードされた operator<< の定義を で囲まない限り、コードがコンパイルされないことnamespace std
です。C++の名前検索の仕組みによるものだと思うのですが、いまだに理解に苦しむところがあります。次のように非テンプレート バージョンを定義しても、
ostream& operator<<(ostream& os, const pair<int,int>& p) {
return os << p.first << "\t" << p.second << endl;
}
それでもコンパイルされません。誰でも理由を説明できますか?