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;
}
ここで、このコードを拡張して、カスタマイズ可能なセパレーターをサポートしたいと考えています。次のアプローチは明らかに機能しません。これは、オペレーターが 2 つのパラメーターのみを受け取ることになっているためです。
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;