How to catch current stream position before istream_iterator

Krzysztof Żelechowski 41 Reputation points
2020-10-03T15:17:37.74+00:00

I am trying to create an extension of class istream_iterator that saves the input stream position before each read. How should I implement the constructor so that it can catch the stream position at the time the constructor was called? Because it is a subclass of istream_iterator, the constructor constructs the base class first; but after the base class has been constructed, the stream position will have changed (this is how istream_iterator works). Short of reimplementing istream_iterator (which is probably the best option because the istream_iterator does not let me ask its underlying stream for its current position, meaning that I need to keep another reference to the same input stream), what are my options here?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,545 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.7K Reputation points
    2020-10-05T16:39:21.367+00:00

    Check the next approach too:

    class MyIterator : istream_iterator<char>
    {
    public:
    
        MyIterator( istream& stream )
            : MyIterator( stream, stream.tellg() )
        {
        }
    
    private:
    
        MyIterator( istream& stream, istream::pos_type pos )
            : istream_iterator( stream ), startPos( pos )
        {
        }
    
        istream::pos_type const startPos;
    };
    

1 additional answer

Sort by: Most helpful
  1. Igor Tandetnik 1,106 Reputation points
    2020-10-03T16:15:11.597+00:00

    Something like this should work:

    MyIterator::MyIterator(istream& stream)
        : istream_iterator((cur_pos = stream.tellg(), stream)) {}