Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator bitwise left shift

Tags:

c++

c++11

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.

like image 432
LarsA Avatar asked Nov 20 '25 13:11

LarsA


1 Answers

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.

like image 178
Ilya Popov Avatar answered Nov 23 '25 04:11

Ilya Popov