This is the sample code I've written, just a simple version to test out an iterator implementation:
template <typename T> struct ArrayIterator { using value_type = typename T::value_type; using pointer = value_type*; using reference = value_type&; using self = ArrayIterator; pointer ptr; ArrayIterator() : ptr{nullptr} {} ArrayIterator(pointer ptr) : ptr{ptr} {} reference operator*() { return *ptr; } bool operator==(self const& other) const { return ptr == other.ptr; } bool operator!=(self const& other) const { return !(*this == other); } self operator++() { ++ptr; return *this; } self operator++(int) { auto copy = *this; ++ptr; return copy; } }; template <typename T, size_t size> struct Array { T arr[size]; using value_type = T; using iterator = ArrayIterator<Array<T, size>>; iterator begin() { return iterator(arr); } Array() : arr{1, 3, 4, 22, 3} {} iterator end() { return iterator(arr + size); } }; int main() { using array = Array<int, 5>; array arr; } Assuming everything is public, and we only pass int as type parameter, and the array has the default constructor just to test range-based for loop. It works.
My question is, why can't we use inheritance? Something like this:
template <typename T, size_t size> struct Array : ArrayIterator<Array<T, size>> {} If used, I get the following error (compiler is clang 11):
first.cpp:46:34: error: no type named 'value_type' in 'Array<int, 5>' using value_type = typename T::value_type; ~~~~~~~~~~~~^~~~~~~~~~ first.cpp:82:16: note: in instantiation of template class 'ArrayIterator<Array<int, 5>>' requested here struct Array : ArrayIterator<Array<T, size>> { ^ first.cpp:101:9: note: in instantiation of template class 'Array<int, 5>' requested here array arr; ^ 1 error generated I can’t understand what's going on.
ArrayfromArrayIterator? An array is not an iterator.