Re: ostream_iterator compile error
smith7005 ha scritto:
Hello,
Below is (what seems to be) a fairly simple application of the
ostream_iterator, but it fails to compile. Can someone identify/
correct the error?
-Thanks!
#include <iostream>
#include <iterator>
using namespace std;
struct Foo
{
int data;
};
ostream& operator<< (ostream& os, const Foo& f)
{
return os << f.data;
}
ostream& operator<< (ostream& os, const pair<int, int>& p)
{
return os << p;
}
int main()
{
Foo f;
cout << f; //ok
ostream_iterator<Foo> foo_iter(cout);
foo_iter = f; //ok
Actually, this compiles and work by a mere accident. ostream_iterator
should always be written to with the form:
*foo_iter = f;
The fact that ostream_iterator::operator* return *this is something you
should not rely to.
pair<int, int> my_pair;
cout << my_pair; //ok
ostream_iterator<pair<int, int> > pair_iter(cout);
pair_iter = my_pair; //ERROR: no appropriate match
for operator<<
Ditto, should be *pair_iter = my_pair;
Ah! This is a typical problem with ADL. As there's no operator<< visible
at the point of definition of ostream_iterator::operator=, operator<<
found only through ADL in the second lookup phase of the template
instantiation process. Unfortunately all the arguments (std::ostream and
std::pair) are defined in the namespace std, so the only associated
namespace is std. This means that global namespace is not searched, so
your operator<<, which is defined in the global namespace, is not found.
Compare that with the Foo case: as Foo is one of the arguments of
operator<< and is defined in the global namespace, the associated
namespaces are std and the global, so both are searched and your
operator<< is found.
You should declare your operator>> into the std namespace to make it
work. Unfortunately, by defining operator<< in namespace std, you would
be violating 17.6.4.2.1/1 and the behaviour of the entire program would
become undefined... :(
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]