map.hpp 1.2 KB

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