What are the differences between streampos and pos_type, streamoff and off_type?

前端 未结 1 483
小鲜肉
小鲜肉 2021-01-12 05:40

What are the differences between streampos and pos_type, streamoff and off_type, except they are defined differently. Wha

相关标签:
1条回答
  • 2021-01-12 05:41

    std::basic_istream and std::basic_ostream both take two template types, CharT and Traits. Given a class A that is derived from one of the basic-streams, the Traits data type can be retrieved as

    A::traits_type
    

    According to §21.2 of the C++ standard, this data type must provide the following member types:

    char_type // must be identical to CharT of the basic-stream
    off_type
    pos_type
    

    (and some further data types irrelevant to the present question). Given the way the std::basic_istream<>::seekg() method is defined, the intended meaning of off_type and pos_type is:

    • pos_type is used for absolute positions in the stream
    • off_type is used for relative positions

    So if you want to use the absolute version of seekg(), the data type you should declare is A::pos_type (which is the same as A::traits_type::pos_type). For the relative version it is A::off_type.

    Regarding std::streampos and std::streamoff: These are defined, too, by the standard as the data types that are used for the default version of the traits_type. In other words, if you do not explicitly specify the Traits template parameter, the A::pos_type will in fact be std::streampos, and A::off_type will in fact be std::streamoff.

    If you create your own version of Traits and want to use it with standard library templates like std::basic_istream<> etc., you must include typedefs for pos_type and off_type (and a lot of other data types), and ensure they comply with §27.2.2 and §27.3 of the standard.

    0 讨论(0)
提交回复
热议问题