streampos和pos_type,streamoff和off_type之间有什么区别?

Mar*_*tin 7 c++

之间有什么区别streampospos_type,streamoff并且off_type,除非他们被不同的定义.我应该用什么basic_stream<>::seek功能?

jog*_*pan 11

std::basic_istream并且std::basic_ostream都采用两种模板类型,CharTTraits.给定从其中一个基本流派生的类A,Traits可以检索数据类型

A::traits_type
Run Code Online (Sandbox Code Playgroud)

根据C++标准的第21.2节,此数据类型必须提供以下成员类型:

char_type // must be identical to CharT of the basic-stream
off_type
pos_type
Run Code Online (Sandbox Code Playgroud)

(以及与当前问题无关的一些其他数据类型).由于道路std::basic_istream<>::seekg()被定义方法的本意off_typepos_type是:

  • pos_type 用于流中的绝对位置
  • off_type 用于相对位置

因此,如果您想使用绝对版本seekg(),您应该声明的数据类型A::pos_type(与之相同A::traits_type::pos_type).对于它的相对版本A::off_type.

关于std::streamposstd::streamoff:这些也被标准定义为用于默认版本的数据类型traits_type.换句话说,如果你没有明确指定的Traits模板参数时,A::pos_type在事实上std::streampos,和A::off_type在事实上std::streamoff.

如果您创建自己的版本Traits并希望将其与标准库模板std::basic_istream<>等一起使用,则必须包含typedef for pos_typeoff_type(以及许多其他数据类型),并确保它们符合§27.2.2和§27.3的标准.

  • +1,进一步说明 - "pos_type"不是标量数字,它还包括有关文件中该位置的文本编码状态的信息.其预期目的是*返回*到先前遇到的位置,而`off_type`可以去预先计算的某个位置. (6认同)