ADL: Argument Dependent Lookup

Tags:

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;
}
&#91;/code&#93;

Yes, it's because operator&lt;&lt; pair&lt;...&gt; is not defined. So, let's define it.

&#91;code lang="cpp"&#93;
ostream& operator<<(ostream& os, const pair<string, int>& p)
{
    os << p.first << ", " << p.second << endl;
}
&#91;/code&#93;

Now the program compiles. But, wait a minute. My fancy ostream_iterator doesn't do what it have to do.

&#91;code lang="cpp"&#93;
#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.