What is the recommended approach for updating an object after creation with a stream of data? I would like to avoid using a number of SetXX methods.
Say I have a class that looks like this;
class Model
{
public:
Model(int, double, std::string);
private:
int a;
double b;
std::string c;
};
One approach to solving this was adding operator;
friend Model& operator<<(Model&, std::stringstream&)
The usage of the above code;
// create model
Model model(...);
// do stuff
// update model later
model << stream;
This approach compile and runs.
Just wondering if this is a good approach and if it has any flaws \ limitations? Notice that most example online using operator<< use it differently than what I am doing above.
I would suggest to follow the same notation as in the standard library: use operator>> for input and return reference to the stream, not the Model. This way it will be more readable for the others (who are familiar with the standard library but not your notation), and it will allow for chained inputs:
friend std::istream & operator>>(std::istream & s, Model & m)
{
m.data = ...
return s;
}
Model m1, m2;
std::cin >> m1 >> m2;
As std::istringstream is derived from std::istream, this operator will work for it as well as all other input stream types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With