c++iteratordistancedifferenceiterator-traits

Is There an Example of an Iterator Which Wouldn't use ptrdiff_t as its difference_type?


I see that iterator_traits always defines a difference_type: https://en.cppreference.com/w/cpp/iterator/iterator_traits#Member_types

I'm just wondering why, wouldn't that be ptrdiff_t for every type? Is there an example of an iterator which doesn't use ptrdiff_t? And if not why isn't difference_type eliminated from iterator_traits and ptrdiff_t used everywhere?


Solution

  • A basic output iterator, with std::ostream_iterator being one example, may not need a difference type at all.

    Since it's meant to be a "fire and forget" sort of iterator, it usually doesn't make much sense to obtain a difference between two such iterators. The mere act of writing to one copy may invalidate all other copies. So it will not need to define a difference type, and should not be forced to do so artificially (or have the type forced on it).