- 반복자를 증가시키는 operator++
- 반복자를 역참조하고 반복자가 가리키는 값에 접근하는 operator*
- 다른 반복자와 비항등성을 비교하는 operator!=
- begin(), end() 함수
#include <stdexcept>
#include <iostream>
template <typename T, const size_t Size>
class dummy_array {
private:
T data[Size] = {};
public:
const T& GetAt(const size_t idx) const {
if (idx < Size) { return data[idx]; }
throw std::out_of_range("index out of range");
}
void SetAt(const size_t idx, const T& value) {
if (idx < Size) { data[idx] = value; }
else {
throw std::out_of_range("index out of range");
}
}
size_t GetSize() const { return Size; }
};
// 반복자 클래스의 최소 구현
template <typename T, typename C, const size_t Size>
class dummy_array_iterator_type {
private:
size_t idx;
C& collection;
public:
dummy_array_iterator_type(C& collection, const size_t idx)
: idx(idx), collection(collection) {}
bool operator!=(const dummy_array_iterator_type& other) const {
return idx != other.idx;
}
const T& operator*() const {
return collection.GetAt(idx);
}
const dummy_array_iterator_type& operator++() {
++idx;
return *this;
}
};
//반복자 이름 템플릿
template <typename T, const size_t Size>
using dummy_array_iterator =
dummy_array_iterator_type<T, dummy_array<T, Size>, Size>;
template <typename T, const size_t Size>
using dummy_array_const_iterator =
dummy_array_iterator_type<T, const dummy_array<T, Size>, Size>;
//begin(), end() 함수
template <typename T, const size_t Size>
inline dummy_array_iterator<T, Size> begin(dummy_array<T, Size>& collection) {
return dummy_array_iterator<T, Size>(collection, 0);
}
template <typename T, const size_t Size>
inline dummy_array_iterator<T, Size> end(dummy_array<T, Size>& collection) {
return dummy_array_iterator<T, Size>(collection, collection.GetSize());
}
template <typename T, const size_t Size>
inline dummy_array_const_iterator<T, Size> begin(const dummy_array<T, Size>& collection) {
return dummy_array_const_iterator<T, Size>(collection, 0);
}
template <typename T, const size_t Size>
inline dummy_array_const_iterator<T, Size> end(const dummy_array<T, Size>& collection) {
return dummy_array_const_iterator<T, Size>(collection, collection.GetSize());
}
auto main() -> int {
dummy_array<int, 3> arr;
arr.SetAt(0, 1);
arr.SetAt(1, 10);
arr.SetAt(2, 100);
for (auto& n : arr) {
std::cout << n << std::endl;
}
}