map.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #pragma once
  2. namespace stream { namespace detail {
  3. template <typename T, typename R> class map_iterator {
  4. public:
  5. map_iterator(std::function<R(T const &)> f, iterator<T> && impl)
  6. : fun_(f), impl_(std::forward<iterator<T>>(impl)) {}
  7. R operator*() { return fun_(*impl_); }
  8. map_iterator & operator++() {
  9. ++impl_;
  10. return *this;
  11. }
  12. bool operator==(map_iterator const & rhs) const { return impl_ == rhs.impl_; }
  13. private:
  14. std::function<R(T const &)> fun_;
  15. iterator<T> impl_;
  16. };
  17. template <typename T, typename R> class map_stream {
  18. public:
  19. template <typename F>
  20. map_stream(F && func, stream_base<T> const & sb)
  21. : fun_(func), source_(sb) {}
  22. iterator<R> begin() { return {map_iterator<T, R>{fun_, source_.begin()}}; }
  23. iterator<R> end() { return {map_iterator<T, R>{fun_, source_.end()}}; }
  24. private:
  25. std::function<R(T const &)> fun_;
  26. stream_base<T> source_;
  27. };
  28. template <typename T>
  29. template <typename F>
  30. stream_base<traits::mapped_t<T, F>> stream_base<T>::map(F && func) && {
  31. return std::make_shared<map_stream<T, traits::mapped_t<T, F>>>(
  32. func, std::move(*this));
  33. }
  34. template <typename T>
  35. template <typename F>
  36. stream_base<traits::mapped_t<T, F>> stream_base<T>::map(F && func) const & {
  37. return std::make_shared<map_stream<T, traits::mapped_t<T, F>>>(func, *this);
  38. }
  39. }}