Re: Why I must put the "operator<<" reload function into namespace std to
On 11 Mai, 22:49, ?? ?????? <zsp...@gmail.com> wrote:
#include <map>
#include <string>
#include <iterator>
#include <iostream>
Missing includes are: <ostream>/<utility>/<stdlib.h>/<algorithm>
using namespace std;
namespace std
{
//If don't put this function into namespace std , there will be
a
compile error .
template<class _Elem,class _Traits,class K,class V>
basic_ostream<_Elem,_Traits>& operator<<(
basic_ostream<_Elem,_Traits>& s
,
const pair<K,V>& p
)
{
return s<<p.first<<" : "<<p.second;
}
}
template<class _Elem,class _Traits,class K,class V>
basic_ostream<_Elem,_Traits>& operator<<(
basic_ostream<_Elem,_Traits>& s
,
const map<K,V>& m
)
{
copy(m.begin(), m.end(), ostream_iterator<pair<K,V> >(s,
"\n"));
return s;
}
int main()
{
using namespace std;
map<string,string> a;
a["key1"]="value1";
a["key2"]="value2";
cout<<a;
system("pause");
return 0;
}
We had a similar discussion some time ago.
Please read http://tinyurl.com/yvca6w for the
details (If this link does not lead to the correct
entry, please read contribution 14).
The short version is: Don't do that! You are not
allowed to add such an overload to namespace
std which brings you in the realm of undefined
behaviour. The above quoted thread shows in
contribution 14 that there are at least two clean
solutions:
1) Change your operator template overload by a
corresponding function template (e.g. "print") in
your user namespace. Then replace your
std::copy invocation by a std::for_each call
(which uses a special print functor and *not*
operator<< on std::pair) or use an explicit loop.
2) Use a better customizable iterator like
boost::transform_iterator which uses the print-functor
mentioned in (1).
Greetings from Bremen,
Daniel Kr??gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]