Please take note of the updates at the end of this post.
Update: I have created a public project on GitHub for this library!
I would like to have a single template that once and for all takes care of pretty-printing all STL containers via operator<<. In pseudo code, I'm looking for something like this:
template<container C, class T, String delim = ", ", String open = "[", String close = "]">
std::ostream & operator<<(std::ostream & o, const C<T> …在考虑C++迭代器问题时,我编写了这个示例程序:
#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
}
我用gcc编译这个程序,得到典型的100行错误.我相信相关部分是:
it.cc:19:从这里实例化
/usr/include/c++/4.4/bits/stream_iterator.h:191:错误:' ((std :: ostream_iterator>,char,std :: char_traits>)中的'operator <<'不匹配- > std :: ostream_iterator>,char,std :: char_traits> :: _ M_stream << __value'
为什么这会失败?在我的模板中 …