简体   繁体   中英

Can someone explain to me briefly what is std::streampos?

Can you show me some examples with std::streampos ? I am not sure what it is used for and I don't know how to work with it.

I saw in a project in github:

std::streampos pos = ss.tellg();

where ss is std::stringstream .

Why don't we use int pos = ss.tellg() , for example in this case?

Why don't we use int pos = ss.tellg(), for example in this case?

Because std::streampos happens to be the type returned by std::basic_stringstream<char, std::char_traits<char>, std::allocator<char>>::tellg() .

Maybe on one computer it's something that converts cleanly to an int , but not on another. By using the correct type, your code is platform-independant.

Also note that std::streampos is the type returned by the tellg() method of that very specific class, not the type returned by tellg() methods everywhere. Other streams might very well return a different type instead of std::stream_pos , and you should be accounting for that.

The actual cleanest way to choose the correct type for pos is to literally ask the type: "What should I be using to represent positions in the stream?":

std::stringstream::pos_type pos = ss.tellg();

Or just use auto so you don't have to worry about it:

auto pos = some_stream.tellg();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM