你能给我看一些
std::streampos
的例子吗?
我不确定它的用途是什么,也不知道如何使用它。
我在github的一个项目中看到:
std::streampos pos = ss.tellg();
其中
ss
是 std::stringstream
。
为什么我们不使用
int pos = ss.tellg()
,例如在本例中?
为什么我们不使用 int pos = ss.tellg(),例如在本例中?
因为
std::streampos
恰好是std::basic_stringstream<char, std::char_traits<char>, std::allocator<char>>::tellg()
返回的类型。
也许在一台计算机上它可以干净地转换为
int
,但在另一台计算机上则不然。通过使用正确的类型,您的代码是平台无关的。
另请注意,
std::streampos
是该特定类的 tellg()
方法返回的类型,而不是各处 tellg()
方法返回的类型。其他流很可能返回不同的类型而不是 std::streampos
,你应该考虑到这一点。
为
pos
选择正确类型的实际最干净的方法是直接询问类型:“我应该使用什么来表示流中的位置?”:
std::stringstream::pos_type pos = ss.tellg();
或者直接使用
auto
这样你就不用担心了:
auto pos = some_stream.tellg();