c++ fstream - creating own formatting flags -


i need create new flags format of output file. have class

class foo{     bar* members;     ofstream& operator<<(ofstream&);     ifstream& operator>>(ifstream&); }; 

and want use like:

fstream os('filename.xml'); foo f; os << xml << f; os.close(); 

this save xml file.

fstream os('filename.json'); foo f; os << json << f; os.close(); 

and json file.

how can this?

you can create yor own manipulators, either hijacking existing flag or using std::ios_base::xalloc obtain new stream specific memory, e.g. (in implementation file of foo:

static int const manipflagid = std::ios_base::xalloc();  enum {     fmt_xml,        //  becomes default.     fmt_json };  std::ostream& xml( std::ostream& stream ) {     stream.iword( manipflagid ) = fmt_xml;     return stream; }  std::ostream& json( std::ostream& stream ) {     stream.iword( manipflagid ) = fmt_json;     return stream; }  std::ostream& operator<<( std::ostream& dest, foo const& obj ) {     switch ( dest.iword( manipflagid ) ) {     case fmt_xml:         // ...         break;     case fmt_json:         //  ...         break;     default:         assert(0);  //  or log error, or abort, or...     }     return dest; } 

declare xml , json in header, , job done.

(having said this, rather think bit of abuse of manipulators. formats xml go beyond simple, local formatting, , best handled separate class, owns ostream, , writes entire stream, , not individual objects.)


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -