我想爲庫中的std :: string容器提供基於通用行的IO。 由於字符串可能包含空格,因此它是基於行的。 下面的代碼似乎工作正常,但我不確定這是否是最好的方式去或它是否造成一些含糊不清,我沒有把握。對於std :: string的非關聯容器io
#define boostForeach BOOST_FOREACH
template< template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container >
std::ostream& operator<< (std::ostream& o, Container<std::string>const & container){
boostForeach(std::string const& str, container) {
o << str << "\n";
}
return o;
}
template< template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container >
std::istream& operator>> (std::istream& in, Container<std::string>& container){
container.clear();
std::string buf;
while(getline(in, buf)) {
if(buf.empty()) break; //stop if empty line found to separate map from other data
container.insert(container.end(),buf);
}
return in;
}
所以問題是:這是安全和健全的嗎?
你可能想[看看這裏](http://codereview.stackexchange.com/)。 :) – netcoder 2012-07-16 21:27:08
@netcoder:太棒了!不知道這一個,一定會試一試 – Martin 2012-07-16 21:31:20