Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: operator<< for pair<const string, int>

17 views
Skip to first unread message

Bo Persson

unread,
Aug 7, 2016, 1:03:03 PM8/7/16
to
On 2016-08-07 18:20, Ahmet Can ÜN wrote:
> Hi,
>
> I wanted to write the content of a std::map to a file. So i wrote
> operator<< function for pairs.
>
> But i'm getting an error.
> #include <string>
> #include <iomanip>
> #include <iostream>
> #include <fstream>
> #include <map>
> #include <utility>
> #include <iterator>
>
> using namespace std;
>
> template<typename T1, typename T2>
> ostream &operator<<(ofstream &os, pair<T1, T2> rp)
> {
> return os << " " << rp.first << " " << rp.second << '\n';
> }
>
> int main()
> {
>
> ifstream ifs("salk.txt");
> map<string, int> smap;
>
> string s;
>
> while (ifs >> s)
> ++smap[s];
>
> ofstream ofs("ahmet.txt");
>
> copy(smap.begin(),
> smap.end(),
> ostream_iterator<map<string, int>::value_type>
> (ofstream("ahmet.txt")));
>
> return 0;
> }
> This is the error message.
> binary '<<': no operator found which takes a right-hand operand of type
> 'const std::pair<const _Kty,_Ty>' (or there is no acceptable conversion)
>
> When i try to write them without using std::copy i have no problem. The code
> below works fine.
>
> ofs << make_pair("ahmet can", 3);
>

It's all about name lookup.

std::copy, as well as map, pair, string, and ostream_iterator all reside
in namespace std. So that's where the compiler will start looking for an
operator<<. Finding *plenty* of them there, there is no reason to look
in any other namespaces.

Especially not the global namespace, where none of the types involved
come from.


Bo Persson

0 new messages