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. ~iterator() {}
  10. R operator*() { return fun_(*impl_); }
  11. DELEGATE_ITERATOR_IMPL(impl_)
  12. private:
  13. std::function<R(T const&)> fun_;
  14. ::stream::iterator<T> impl_;
  15. };
  16. }
  17. template <typename T, typename R>
  18. class map_stream : public stream_impl<R> {
  19. public:
  20. template <typename F>
  21. map_stream(F&& func, stream_base<T> const& sb) : fun_(func), source_(sb) {}
  22. ~map_stream() override {}
  23. iterator<R> begin() override {
  24. return {map::iterator<T, R>{fun_, source_.begin()}};
  25. }
  26. iterator<R> end() override {
  27. return {map::iterator<T, R>{fun_, source_.end()}};
  28. }
  29. private:
  30. std::function<R(T const&)> fun_;
  31. stream_base<T> source_;
  32. };
  33. template <typename T>
  34. template <typename F>
  35. auto stream_base<T>::map(F&& func) const -> stream_base<map_f<F>> {
  36. using impl_t = map_stream<T, map_f<F>>;
  37. return {std::make_shared<impl_t>(func, *this)};
  38. }
  39. } }