13
In thinking about C++ iterator question, I wrote this sample program:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
template <class T>
std::ostream& operator<<(std::ostream&os, const std::vector<T>& v)
{
os<<"(";
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ", "));
return os<<")";
}
int main()
{
std::vector<int> v(3);
std::vector<std::vector<int> > vv(3, v);
std::cout << v << "\n"; // this line works
std::cout << vv << "\n"; // this line produces error
}
I compile this program with gcc and get the typical 100 lines of errors. The relevant part, I believe, is:
it.cc:19: instantiated from here
/usr/include/c++/4.4/bits/stream_iterator.h:191: error: no match for ‘operator<<’ in ‘((std::ostream_iterator >, char, std::char_traits >)this)->std::ostream_iterator >, char, std::char_traits >::_M_stream << __value’
Why does this fail? In my templated operator<<, I try to specify that any vector, regardless of type, is printable. So why doesn't std::vector<std::vector<>> print?
EDIT: Using the following code in the template function makes it work
#if 0
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ", "));
#else
for(typename std::vector<T>::const_iterator it = v.begin();
it != v.end();
it++) {
os<<(*it)<<", ";
}
#endif