Search code examples
c++operator-overloadingfilestream

Incrementing a streampos Object


I'm trying to do something like this:

for (std::streampos Position = 0; Position < 123; Position++)
{
    // Use Position to access something...
}

However, it appears that std::streampos does not have operator++ overloaded.

Trying to use Position = (Position + 1) results in the following error:

ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:

Is there any workaround for this, or do I have to rely on long unsigned int being big enough for files?


Solution

  • Try a std::streamoff, which represents an offset in a stream. It supports both pre- and post increment/decrement operators.

    The underlying type is implementation defined, but must be able to be consistently converted to both streamsize and fpos (thus, to streampos too)

    Edit to Maxpm's comment: You can apply the streamoff to anywhere, be it ios::beg or an arbitary streampos. Apply it to ios::beg and it behaves like a normal streampos. Apply it to a streampos and you got streampos+streamoff.