Uses of std::reverse_iterator with containers should not require manually including <iterator>
Jiang An

Created on 2021-10-23.00:00:00 last changed 1 month ago


Date: 2021-10-24.11:32:07

Proposed resolution:

This wording is relative to N4901.

  1. Modify [reverse.iterators.general] as indicated:

    -1- Class template reverse_iterator is an iterator adaptor that iterates from the end of the sequence defined by its underlying iterator to the beginning of that sequence.

    -?- In addition to being available via inclusion of the <iterator> header, class template reverse_iterator and function templates in [reverse.iter.cmp] and [reverse.iter.nonmember] are available when any of the following headers are included: <array> ([array.syn]), <deque> ([deque.syn]), <forward_list> ([forward.list.syn]), <list> ([list.syn]), <map> ([associative.map.syn]), <regex> ([re.syn]), <set> ([associative.set.syn]), <span> ([span.syn]), <stacktrace> ([stacktrace.syn]), <string> ([string.syn]), <string_view> ([string.view.synop]), <unordered_map> ([unord.map.syn]), <unordered_set> ([unord.set.syn]), and <vector> ([vector.syn]).

Date: 2021-10-23.00:00:00

Currently it is unspecified whether the definitions of std::reverse_iterator and its related operators are available in <vector>, <array>, etc. So, it's unspecified now whether the following program is well-formed because it's unspecified whether the equality operator is available:

#include <vector>

int main()
  auto v = std::vector<int>(42);
  for (auto it = v.rbegin(); it != v.rend(); ++it);
  for (auto it = std::rbegin(v); it != std::rend(v); ++it);

Such underspecification also leaves the guarantee that std::rbegin, std::rend, std::crbegin, and std::crend are available in some other headers seems not so meaningful. In order to guarantee these function templates can be used meaningfully with containers, users are still required to include <iterator> manually.

I think the standard should guarantee that wherever the member rbegin (that returns std::reverse_iterator) or std::rbegin is provided, the definitions of std::reverse_iterator and its related operators are also provided. This strategy is already implemented by libc++, libstdc++, and MSVC STL, and thus I believe we should standardize it to reduce uncertainty for users.

Note that the situation for std::reverse_iterator is different from LWG 1361, because every operation on std::size_t is still valid when the typedef-name itself is absent, but == and != on std::reverse_iterator fail if the corresponding declarations are unavailable.

Date User Action Args
2021-10-24 10:32:27adminsetmessages: + msg12189
2021-10-23 00:00:00admincreate