cppitertools icon indicating copy to clipboard operation
cppitertools copied to clipboard

dereference operators should be const

Open thomas001 opened this issue 2 years ago • 0 comments

Currently a lot iterators have only non-const operator* or operator-> (for example in groupby).

This is not correct according to the legacy and C++20 iterator concepts:

  • LegacyInputIterator states that *i and i->m should be valid expressions given

    i and j, values of type It or const It

    Note the inclusion of const It here.

  • std::indirectly_readable (which is required by std::input_iterator) has

    requires(const In in) {
      // ...
      { *in } -> std::same_as<std::iter_reference_t<In>>;
      // ....
    } &&
    

    Note that the concept requires *in vor values of const In.

Since iterators are copyable, one can always work around this by copying a const itertools iterator and dereferencing the copy. Yet, this might be inefficient for some iterators. Also, itertools iterators not implementing c++20 iterator concepts will probably make them much less useful in the future. Finally, there are other range and iterator adapter libraries out there which might assume a const iterator is dereferenceable.

For some iterators in itertools the fix seems to be straightforward by adding const to the operators. Others, like groupby, seem to require more changes.

thomas001 avatar Feb 23 '23 13:02 thomas001