Bitwise left shift operator
What is the recommended approach for updating an object after being created with a data stream? I would like to avoid using multiple SetXX methods.
Let's 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 issue was to add an operator:
friend Model& operator<<(Model&, std::stringstream&)
Using the above code;
// create model
Model model(...);
// do stuff
// update model later
model << stream;
This approach compiles and runs.
Just wondering if this is a good approach and if it has any disadvantages / limitations? Note that most of the time online using the <operator use it differently than what I am doing above.
source to share
I suggest following the same notation as in the standard library: use operator>>
stream references for input and return, not Model
. This way it will be more readable to others (who are familiar with the standard library, but not your notes), and this 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;
Since it std::istringstream
is derived from std::istream
, this operator will work for it as well as for all other types of input streams.
source to share
I would consider writing a method update
that takes a stream instead of using an operator. The downside to using an operator <<
is, as you stated, that it is not usually used for this purpose, which is likely to annoy anyone looking at your code that doesn't know how you implemented the operator. stream >> model
more commonly used, as pointed out in the comments.
source to share