Re: How to copy maps to ostream_iterators?
Carl Barron wrote:
In article <4456d1ff@mamba.>, Siegfried Heintze
<siegfried@heintze.com> wrote:
The syntax error messages are telling me there is no
function operator<< defined to accept a std::pair. This is
not true:
Its true since operator << ()'s args are in namespace std and
operator << is called from namespace std [in
std::ostream_iterator<...>() lookup only occurs in namespace
std.
as you can see I have defined such a function. I've seen
this work with other compilers. I've tried
std::ostream& operator<<(std::ostream&os, const
std::pair<std::string,std::string>&x){ .... }
but that does not work either.
It might be worth pointing out that the reason it works with
older compilers is that they don't use two phase lookup. It
will still work with modern compilers outside of a template. It
is only when instantiating a template that lookup is restricted
to ADL. And then only for dependant names, and for the lookup
which takes place in the instantiation context.
[...]
3) STRICTLY ILLEGAL in terms of the standard. put your
operator << () in namespace std.
Illegal, but it will work everywhere.
More importantly, of course, overloading an operator<< for any
standard class is something that you would never want to do
outside of small experimental programs. Why should your
component get the priviledge, and no other?
My usual solution for this sort of thing is a class which
implicitly converts to or from the standard type. In this case,
something along the lines of:
class MyPair
{
public:
MyPair( map_type::value_type const& v ) : myValue( v ) {}
friend std::ostream& operator<<( std::ostream& dest,
MyPair const& obj ) ;
private:
map_type::value_type myValue ;
} ;
Something along the lines of:
std::copy( m.begin(), m.end(),
std::ostream_iterator< MyPair >( std::cout ) ) ;
Should then do the job.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]