【发布时间】:2013-08-10 14:32:31
【问题描述】:
我经常想将 stl 容器写入 ostream。 以下代码可以正常工作(至少对于向量和列表):
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;
}
现在我想扩展此代码以支持可自定义的分隔符。以下方法显然行不通,因为该运算符应该只采用两个参数。
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;
}
不借助单例或全局变量可以实现这样的目标吗?
理想的情况是引入自定义标志或流操纵器,例如std::fixed。这样就可以写了
std::cout << streamflags::tabbed << myContainer;
【问题讨论】:
标签: c++ io stream operator-overloading