I have a library function that works on arbitrary containers. Basically it prints elements. For a bidirectional/random-access container it prints first and last, for unidirectional only first. Recognizing and using bidirectionality hinges on a working --container.end()
. This worked for std::array
in C++17, but in C++20 std::array
has ConstexprIterator
instead of LegacyRandomAccessIterator
.
Reading https://en.cppreference.com/w/cpp/named_req/ConstexprIterator it seems that ConstexprIterator
really doesn't have operator--
and instead has something to do with cats???
So my question is: WHY isn't ConstexprIterator
random-access or at least bidirectional? I mean, if it works at compile time then it really should be random-access.
in c++20
std::array
has ConstexprIterator instead of LegacyRandomAccessIterator
Not "instead of".
https://en.cppreference.com/w/cpp/container/array (bold mine)
iterator
— LegacyRandomAccessIterator and ConstexprIterator (since C++20) that is a LiteralType (since C++17)
WHY isn't ConstexprIterator random access or at least bidirectional
An iterator can have any iterator category in addition to being ConstexprIterator.
ConstexprIterator requires that all operations required by a category (that an iterator claims to conform to) work at compile-time, nothing more.
Meow!
So my question is: WHY isn't ConstexprIterator random access or at least bidirectional?
Because that would prevent iterators that aren't random access or bidirectional from being constexpr iterators. Such limitation would be undesirable.
This is similar to how neither mutable iterator nor constant iterator are limited to certain iterator category. These are additional concepts that can apply to iterator of any category.
Reading https://en.cppreference.com/w/cpp/named_req/ConstexprIterator it seems that ConstexprIterator really doesn't have operator--
Regadless of the linked page being out of date (and a non-normative source), this is actually true. A constexpr iterator doesn't necessarily have operator--.
Why ConstexprIterator from std::array isn't bidirectional/random access?
It is random access. Standard says (latest draft):
[array.overview]
The header defines a class template for storing fixed-size sequences of objects. An array is a contiguous container.
[container.requirements.general]
A contiguous container is a container whose member types iterator and const_iterator meet the Cpp17RandomAccessIterator requirements ([random.access.iterators]) and model contiguous_iterator ([iterator.concept.contiguous]).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With