On 19 Oct, 23:28, mojmir <svobod...@gmail.com> wrote:
hello,
i am trying to dump whole map container to ostream like this:
template<typename T, typename U>
inline
std::ostream & operator<< (std::ostream & s, std::pair<T,U> const & p)
{
s << "<" << p.first << "," << p.second << ">";
return s;
}
template<typename K, typename T>
inline
std::ostream & operator<< (std::ostream & s, std::map<K,T> const & m)
{
s << "(";
typedef typename std::map<K,T>::value_type t;
std::copy(m.begin(), m.end(), std::ostream_iterator<t>(s, " "));
s << ")";
return s;
}
but the copy line fails to compile and i am unable to guess why.
I assume that you have the correct #includes?
#include <algorithm> // For std::copy
#include <iterator> // For std::ostream_iterator
#include <map> // For std::map
#include <ostream> // For std::ostream
#include <utility> // For std::pair
Beyond that, whether the code works or not will depend exactly what
your test case looks like, but there definitely is scope to be bitten
by a fairly subtle problem. The following test case, for example,
should exhibit the problem:
#include <iostream>
#include <string>
int main() {
std::map< std::string, int > m;
std::cout << m;
}
The fundamental problem is to do with name lookup of operator<<, and
because you have put it in the global namespace it is not being
found. The short answer is that you can fix this by moving the two
operator<<s into namespace std -- technically this isn't legal as
you're not really allowed to put overloaded operators into namespace
std, but it's probably the least worst solution.
to make the code compiles.
Because within std::ostream_iterator, only namespace std is visible.
[ comp.lang.c++.moderated. First time posters: Do this! ]