Search code examples
c++type-conversionstandardsfilestream

Can [std::streampos] be converted to [size_t] implicitly?


#include <fstream>

int main()
{
    std::ifstream fin{ "" };
    size_t n = fin.tellg(); // ok
}

The code compiles ok. However, according to cppreference, I find fin.tellg() is a type of std::fpos, which doesn't define the ability to convert itself to size_t implicitly.

Any explanations?


Solution

  • You are right about the fact that it returns an std::fpos. Now let's look at how it's defined:

    template<class _Statetype>
        class fpos {<...>}
    

    fpos also does have a conversion operator for converting into the streamoff type which is "stream offset" type:

    __CLR_OR_THIS_CALL operator streamoff() const
        {   // return offset
        return ((streamoff)(_Myoff + _FPOSOFF(_Fpos)));
        }
    

    On my machine streamoff happens to be defined as typedef _Longlong streamoff;, I would believe it's something similar on your machine. This is why it can be converted to type_t, however nothing prevents it from being larger than type_t, so be careful.