[英]Can someone explain to me briefly what is std::streampos?
Can you show me some examples with std::streampos
?你能给我看一些
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:我在github的一个项目中看到:
std::streampos pos = ss.tellg();
where ss
is std::stringstream
.其中
ss
是std::stringstream
。
Why don't we use int pos = ss.tellg()
, for example in this case?为什么我们不使用
int pos = ss.tellg()
,例如在这种情况下?
Why don't we use int pos = ss.tellg(), for example in this case?
为什么我们不使用 int pos = ss.tellg(),例如在这种情况下?
Because std::streampos
happens to be the type returned by std::basic_stringstream<char, std::char_traits<char>, std::allocator<char>>::tellg()
.因为
std::streampos
恰好是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.也许在一台计算机上它可以干净地转换为
int
,但在另一台计算机上不是。 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.另请注意,
std::streampos
是非常特定的 class 的 tellg( tellg()
方法返回的类型,而不是任何地方的tellg()
方法返回的类型。 Other streams might very well return a different type instead of std::stream_pos
, and you should be accounting for that.其他流很可能返回不同的类型而不是
std::stream_pos
,您应该考虑到这一点。
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?":为
pos
选择正确类型的实际最简洁的方法是直接询问类型:“我应该使用什么来表示 stream 中的位置?”:
std::stringstream::pos_type pos = ss.tellg();
Or just use auto
so you don't have to worry about it:或者只使用
auto
这样你就不用担心了:
auto pos = some_stream.tellg();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.