Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterators to arrays of different sizes

The following code compiles fine on my system:

#include <array>
#include <type_traits>

static_assert(std::is_same<std::array<int, 5>::iterator,
                           std::array<int, 7>::iterator>::value, ":(");

Is that behavior guaranteed by the standard? Is the iterator type independent of the array size?

If it is guaranteed, is there any way to abstract from the element type and ignore the size?

template<typename T, size_t n>
void foobar(std::array<T, n>::iterator it)

That is, is there any way to write the above array-specific code without mentioning the size n?

Note that I do not want to resort to T*, even though in release mode the iterator probably is a T*.

like image 640
fredoverflow Avatar asked Oct 10 '12 16:10

fredoverflow


2 Answers

No, there are no guarantees. The standard just says

typedef implementation-defined    iterator;

The iterator type could be a plain pointer, a class that is a member of the array, or a separate class wrapping the plain pointer.

If it is a member class, it will depend on the array size. Otherwise likely not.

like image 137
Bo Persson Avatar answered Oct 03 '22 20:10

Bo Persson


No, it's not guaranteed. Each array type array<T, size_t> has a nested member typedef named iterator whose type is implementation defined.

like image 24
Pete Becker Avatar answered Oct 03 '22 20:10

Pete Becker