Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't ConstexprIterator from std::array bidirectional/random-access?

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???

enter image description here

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.

like image 922
MateuszL Avatar asked Sep 30 '20 19:09

MateuszL


2 Answers

in c++20 std::array has ConstexprIterator instead of LegacyRandomAccessIterator

Not "instead of".

https://en.cppreference.com/w/cpp/container/array (bold mine)

iteratorLegacyRandomAccessIterator 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!

like image 195
HolyBlackCat Avatar answered Oct 14 '22 03:10

HolyBlackCat


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]).

like image 42
eerorika Avatar answered Oct 14 '22 04:10

eerorika