你能给我看一些例子吗std::streampos?我不确定它的用途是什么,也不知道如何使用它。
我在github的一个项目中看到:
std::streampos pos = ss.tellg();
Run Code Online (Sandbox Code Playgroud)
哪里。ssstd::stringstream
int pos = ss.tellg()例如,在这种情况下我们为什么不使用, 呢?
小智 6
例如,在本例中,我们为什么不使用 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();
Run Code Online (Sandbox Code Playgroud)
或者只是使用auto这样你就不必担心它:
auto pos = some_stream.tellg();
Run Code Online (Sandbox Code Playgroud)