I often want to write a stl container for ostream. The following code works fine (at least for vector and list):
template< typename T ,template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container > std::ostream& operator<< (std::ostream& o, Container<T>const & container){ typename Container<T>::const_iterator beg = container.begin(); while(beg != container.end()){ o << *beg++; if (beg!=container.end()) o << "\t"; } return o; }
Now I want to extend this code to support custom separators. The following approach obviously does not work , since the operator must accept only two parameters.
template< typename T ,template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container > std::ostream& operator<< (std::ostream& o, Container<T>const & container,char* separator){ typename Container<T>::const_iterator beg = container.begin(); while(beg != container.end()){ o << *beg++; if (beg!=container.end()) o << separator; } return o; }
Is it possible to achieve something similar without resorting to singles or global variables?
It would be ideal to introduce a custom flag or stream manipulator, such as std::fixed . Then one could write
std::cout << streamflags::tabbed << myContainer;
source share