Properly overloading >> Operator in C++ -


i couldn't find proper example of how properly.

the following code written in faq.

std::istream& operator>>(std::istream& is, t& obj) {   // read obj stream  if( /* no valid object of t found in stream */ )     is.setstate(std::ios::failbit);  return is; } 

how check if "no valid object of t found in stream" ?

you can follows:

save current possition in input stream by:

streampos pos = is.tellg() 

read data stream char buffer:

char tmp_buf[expected_size]; read(tmp_buf, expected_size);  // try create temporary object read data t tmp_obj = t::fromcharbuffer(tmp_buf) // need implement  // if valid object copy destination obj = tmp_obj  // in case of error revert previous stream position if (error)     is.seekg(pos)  return 

ok, ignore above, wrong:

this topic can better:

what's right way overload stream operators << >> class?

more elegant solution:

your have interprate/validate data particular class need implement functionality somewhere. have 3 options:

  1. in particular class
  2. in base class
  3. in friend class of particular class (best option)

my implementation of approach no.3

class someclassparser: {      // implement functionality of creating someclass stream.      static someclass fromstream(ifstream &if)      {          // stream reading here , return someclass object          // or throw parsing exception      }  };  class someclass: {     public:         friend someclassparser;         // points parser class         typedef someclassparser parser;         ... };  template<typename t> ifstream& operator<<(ifstream &if, t& obj) {     // type independent work, depending on needs:     // logging, stream recovery, error handling etc;     // i'm not telling it's or bad approach recover stream after failure     // need here      // save stream     streampos pos = is.tellg()     try     {         obj = t::parser::fromstream(if);     }     catch (int e):     {         // restore stream         is.seekg(pos);     } } 

with solution not destroy old object in case parsing error ocurrs.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -