Here is the pattern for an extractor:
template<class charT, class Traits> basic_istream<charT, Traits>& operator >> (basic_istream<charT, Traits >& is, UserDefinedType& x) { ios_base::iostate err = 0; try { typename basic_istream<charT, Traits>::sentry ipfx(is); if(ipfx) { // Do whatever has to be done! // Typically you will access the stream's locale or buffer. // Don't call stream member functions here in MT environments! // Add state bits to the err variable if necessary, e.g. // if () err |= ios_base::failbit; } } // try catch(...) //1 { bool flag = FALSE; try { is.setstate(ios_base::failbit); } //2 catch( ios_base::failure ) { flag= TRUE; } //3 if ( flag ) throw; //4 } if ( err ) is.setstate(err); //5 return is; }
Similarly, the pattern for the inserter looks like this:
template<class charT, class Traits> basic_ostream<charT, Traits>& operator << (basic_ostream<charT, Traits >& os, const UserDefinedType& x) { ios_base::iostate err = 0; try { typename basic_ostream<charT, Traits>::sentry opfx(os); if(opfx) { // Do whatever has to be done! // Typically you will access the stream's locale or buffer. // Don't call stream member functions here in MT environments! // Add state bits to the err variable if necessary, e.g. // if () err |= ios_base::failbit; // Reset the field width after usage, i.e. // os.width(0); } } //try catch(...) { bool flag = FALSE; try { os.setstate(ios_base::failbit); } catch( ios_base::failure ) { flag= TRUE; } if ( flag ) throw; } if ( err ) os.setstate(err); return os; }
©Copyright 1998, Rogue Wave Software, Inc.
Send mail to report errors or comment on the documentation.