From 5e9026c6155948cd089df3bf63710b62f180feb6 Mon Sep 17 00:00:00 2001 From: Anton Bachin Date: Sun, 3 May 2015 15:24:44 -0400 Subject: [PATCH] Factored out common iterator code. --- enum.h | 97 ++++++++++++++++++++-------------------------------------- 1 file changed, 33 insertions(+), 64 deletions(-) diff --git a/enum.h b/enum.h index 570e705..fe5fb27 100644 --- a/enum.h +++ b/enum.h @@ -54,9 +54,6 @@ namespace _enum { -// Forward declaration of _Internal, for use in a friend declation in _Iterable. -template class _Enum; - // TODO Make these standard-compliant. /// Template for iterable objects over enum names and values. /// @@ -101,70 +98,50 @@ template class _Enum; template class _Iterable; -template -class _ValueIterator { +template +class _BaseIterator { public: - constexpr EnumType operator *() const - { - return EnumType::_value_array[_index]; - } + Derived& operator ++() + { ++_index; return static_cast(*this); } + constexpr bool operator ==(const Derived &other) const + { return other._index == _index; } + constexpr bool operator !=(const Derived &other) const + { return other._index != _index; } - _ValueIterator& operator ++() - { - if (_index < EnumType::_size) - ++_index; - - return *this; - } - - constexpr bool operator ==(const _ValueIterator &other) const - { - return other._index == _index; - } - - constexpr bool operator !=(const _ValueIterator &other) const - { - return !(*this == other); - } - - private: - constexpr _ValueIterator(size_t index) : _index(index) { } + protected: + constexpr _BaseIterator(size_t index) : _index(index) { } size_t _index; +}; + +template +class _ValueIterator : + public _BaseIterator> { + + using _Super = _BaseIterator>; + + public: + constexpr EnumType operator *() const + { return EnumType::_value_array[_Super::_index]; } + + private: + using _Super::_Super; friend _Iterable>; }; template -class _NameIterator { +class _NameIterator : + public _BaseIterator> { + + using _Super = _BaseIterator>; + public: const char* operator *() const - { - return EnumType::_getProcessedName(_index); - } - - _NameIterator& operator ++() - { - if (_index < EnumType::_size) - ++_index; - - return *this; - } - - constexpr bool operator ==(const _NameIterator &other) const - { - return other._index == _index; - } - - constexpr bool operator !=(const _NameIterator &other) const - { - return !(*this == other); - } + { return EnumType::_getProcessedName(_Super::_index); } private: - constexpr _NameIterator(size_t index) : _index(index) { } - - size_t _index; + using _Super::_Super; friend _Iterable>; }; @@ -174,16 +151,8 @@ class _Iterable { public: using iterator = Iterator; - constexpr iterator begin() const - { - return iterator(0); - } - - constexpr iterator end() const - { - return iterator(EnumType::_size); - } - + constexpr iterator begin() const { return iterator(0); } + constexpr iterator end() const { return iterator(EnumType::_size); } constexpr size_t size() const { return EnumType::size(); } private: