Quote:Original post by ffx
Not like that. Consider code :My problem is that if user wanted to save to standard ofstream I need to call istream operator<< but if he wanted to save in binary I need to call member function write. You see my problem? Anyway, I've come to solution.ostream os(/* here goes archive type, binary, text or xml or any other*/);os << fVal;
Don't worry, I don't plan to release bad article. I've seen to many of those.
Well, changing the behavior of std::ostream isn't a good idea IMHO - if you meant oarchive as in your original example, then my code example should work as intended assuming the reference refers to the ostream the user wants to work with - although my code example depends on the boolean "binary" (which would be set in the oarchive ctor as the flags were read). If you want to go with an ostream inheriting class (so you can pass an oarcive to an "ostream &") things might be slightly trickier since then you WILL have to work with the compiler-specific standard headers. A more complete example, using a class-local fstream:
class oarchive{ std::ofstream fs; bool binary;public: oarchive( const char * filename , std::ios_base::openmode mode = std::ios_base::out | std::ios_base::trunc ) : fs(filename,mode) { binary = ( mode & std::ios_base::binary ); } void open( const char * filename , std::ios_base::openmode = std::ios_base::out | std::ios_base::trunc ) { binary = ( mode & std::ios_base::binary ); fs.open( filename , openmode ); } template < typename T > oarchive & operator<<( const T & value ) { if (binary) { os.write(reinterpret_cast<const char *>(&value),sizeof(T)); } else { os << value; } return *this; }};