map.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 {
  13. return impl_ == rhs.impl_;
  14. }
  15. private:
  16. std::function<R(T const &)> fun_;
  17. iterator<T> impl_;
  18. };
  19. template <typename T, typename R> class map_stream {
  20. public:
  21. template <typename F>
  22. map_stream(F && func, stream_base<T> const & sb)
  23. : fun_(func), source_(sb) {}
  24. iterator<R> begin() { return {map_iterator<T, R>{fun_, source_.begin()}}; }
  25. iterator<R> end() { return {map_iterator<T, R>{fun_, source_.end()}}; }
  26. private:
  27. std::function<R(T const &)> fun_;
  28. stream_base<T> source_;
  29. };
  30. template <typename T>
  31. template <typename F>
  32. stream_base<traits::mapped_t<T, F>> stream_base<T>::map(F && func) && {
  33. return std::make_shared<map_stream<T, traits::mapped_t<T, F>>>(
  34. func, std::move(*this));
  35. }
  36. template <typename T>
  37. template <typename F>
  38. stream_base<traits::mapped_t<T, F>> stream_base<T>::map(F && func) const & {
  39. return std::make_shared<map_stream<T, traits::mapped_t<T, F>>>(func, *this);
  40. }
  41. }}