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.
I'd consider writing an update
method that takes a stream instead of using the operator. The flaw with using the operator <<
is, as you stated, that it's not usually used for that purpose, which will probably irritate everyone looking at your code that doesn't know how you implemented the operator. stream >> model
is more commonly used, as stated in the comments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.