3

Im working with the book SFML Game Development by Examples and I dont really get what this sentence does. I've never seen something like this

void Anim_Directional::ReadIn(std::stringstream& l_stream){
l_stream >> m_frameStart >> m_frameEnd >> m_frameRow
  >> m_frameTime >> m_frameActionStart >> m_frameActionEnd;
}
NMC
  • 41
  • 1
  • 5
  • 2
    This capability has been part of C++ for a long, long time. Since you have never seen something like this before, it appears you are in dire need of a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Eljay Mar 17 '19 at 13:03

2 Answers2

6

In C++ they got the "bright" idea of overloading the rightshift and leftshift operators with streams to represent serialization/deserialization.

stream >> var

means "read var from stream".

Symmetrically

stream << var

mean "put var into stream"

The operation of "streaming" in or out also returns the stream, so you can chain operations like:

stream >> var1 >> var2;

Note that the "streaming" was chosen just because of the look and because the priority was considered reasonable, but it's still just an overloaded operator and implies for example no strict sequence of evaluation. For example in:

stream << f() << g();

may be function g is called (somewhat surprisingly) before function f.

NOTE: the sequencing problem was handled by hammering this special case in last C++ standard (C++17). While it doesn't hold in general it's guaranteed for shift operators (presumably for this specific reason). So in f()+g() may be f is called later than g, but in f()<<g() this cannot happen.

6502
  • 112,025
  • 15
  • 165
  • 265
0

C++ allows you to overload >> and << operators. std::stringstream is a derivative of std::istream and it inherits the >> operator overloads of std::istream.

The std::istream has a bunch of overloads for many common types. You can find a list of them here.

A typical std::istream >> operator overload looks as follows:

std::istream& operator>>(std::istream& stream, YourType& var) {
    /* 
    ** code here to parse and read a 'YourType' into 'var'
    */
    /* var is set */
    return stream; /* return the same stream to allow chaining */
}

When you do some_stream >> YourType_object, the matching >> operator overload is invoked. In the aforementioned case, our operator overload is invoked with stream parameter taking some_stream and var taking YourType_object.

The >> overloads (and << overloads too) intelligently return the stream which they operated; thereby, allowing a series of >> operators to be chained.

Yashas
  • 1,154
  • 1
  • 12
  • 34