Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this right shifts work: stringstream >> unsigned int >> unsigned int? [duplicate]

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;
}
like image 458
NMC Avatar asked Jun 03 '26 19:06

NMC


1 Answers

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 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.

(*) Symmetry is not the correct term as the stream must come first. Allowing expr >> stream for output wouldn't work because of associativity rules (a >> b >> s is parsed as (a >> b) >> s and this cannot be changed with overloads).

like image 59
6502 Avatar answered Jun 06 '26 10:06

6502