ADL is the abbreviation of Argument Dependent Lookup(or Andrew’s Devious Lookup -_-;). Do you know why the following fails to compile?
#include <iostream> #include <map> #include <algorithm> #include <iterator> #include <utility> using namespace std; int main() { map<string, int> m; m["a"] = 1; m["b"] = 2; map<string, int>::iterator i = m.begin(); cout << *i << endl; return EXIT_SUCCESS; } [/code] Yes, it's because operator<< pair<...> is not defined. So, let's define it. [code lang="cpp"] ostream& operator<<(ostream& os, const pair<string, int>& p) { os << p.first << ", " << p.second << endl; } [/code] Now the program compiles. But, wait a minute. My fancy ostream_iterator doesn't do what it have to do. [code lang="cpp"] #include <iostream> #include <map> #include <algorithm> #include <iterator> #include <utility> using namespace std; ostream& operator<<(ostream& os, const pair<string, int>& p) { os << p.first << ", " << p.second << endl; } int main() { map<string, int> m; m["a"] = 1; m["b"] = 2; copy(m.begin(), m.end(), ostream_iterator< pair<string, int> >(cout, " ")); return EXIT_SUCCESS; }
Do you know why this refuses to be compiled? I spent WHOLE DAY TO FIND OUT WHY!!!! And now I got the answer:
Overloading operator<< on std::pair<>.
To my disappoint, I’ve already read an article on ADL before: see here.