Browse Source

Cleaning up implementation of stream::iterator<T>

Samuel Jaffe 8 years ago
parent
commit
2f3ed269e3
1 changed files with 24 additions and 14 deletions
  1. 24 14
      streams/streams.hpp

+ 24 - 14
streams/streams.hpp

@@ -4,18 +4,24 @@
 #include <memory>
 #include <numeric>
 
-#define EQ_MEM(x) x == dynamic_cast<iterator const&>(other).x
-
 #define DELEGATE_ITERATOR_IMPL_BASE(impl) \
-bool operator==(iterator const&other) const { return EQ_MEM(impl); } \
+  bool operator==(iterator const&other) const { \
+    return impl == other.impl; \
+  }
 
 #define DELEGATE_ITERATOR_IMPL(impl) \
-iterator& operator++() { ++impl; return *this; } \
-DELEGATE_ITERATOR_IMPL_BASE(impl)
+  DELEGATE_ITERATOR_IMPL_BASE(impl) \
+  iterator& operator++() { \
+    ++impl; \
+    return *this; \
+  }
 
 std::map<void*, bool> data;
 
 namespace stream {
+#define STREAM_ITERATOR_COPY() \
+  copy(other.copy), dereference(other.dereference), compare(other.compare), destroy(other.destroy), advance(other.advance), type_(other.type_)
+  
   template <typename T>
   class iterator {
   public:
@@ -39,21 +45,25 @@ namespace stream {
     }
     
     iterator(iterator const& other)
-    : copy(other.copy)
-    , dereference(other.dereference)
-    , compare(other.compare)
-    , destroy(other.destroy)
-    , advance(other.advance)
-    , type_(other.type_)
+    : STREAM_ITERATOR_COPY()
     , impl_(copy(other.impl_)) {
     }
     
+    iterator(iterator && other)
+    : STREAM_ITERATOR_COPY()
+    , impl_(other.impl_) {
+      other.impl_ = nullptr;
+    }
+    
     iterator & operator=(iterator const & other) {
-      iterator tmp{other};
-      swap(*this, tmp);
+      return *this = iterator{other};
+    }
+
+    iterator & operator=(iterator && other) {
+      swap(*this, other);
       return *this;
     }
-    
+
     ~iterator() { if (destroy) destroy(impl_); }
     
     T operator*() const { return dereference(impl_); }