SHARE
TWEET

reverse for_each

ulfben Feb 14th, 2020 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iterator>
  2. #include <vector>
  3.  
  4. template<typename T>
  5. class reverse;
  6.  
  7. template<typename T>
  8. class reverse<T&> {
  9. private:
  10.   T& _iterable;
  11. public:
  12.   explicit reverse(T& iterable) : _iterable{iterable} {}
  13.   auto begin() const { return std::rbegin(_iterable); }
  14.   auto end() const { return std::rend(_iterable); }
  15. };
  16.  
  17. template<typename T>
  18. class reverse<T&&> {
  19. private:
  20.   T _iterable;
  21. public:
  22.   explicit reverse(T&& iterable) : _iterable{std::move(iterable)} {}
  23.   auto begin() const { return std::rbegin(_iterable); }
  24.   auto end() const { return std::rend(_iterable); }
  25. };
  26.  
  27. template<typename T>
  28. reverse(T&& v) -> reverse<decltype(std::forward<T>(v))>;
  29.  
  30. //Usage:
  31. void foo(int);
  32. std::vector<int> make_vec();
  33.  
  34. void test_lvalue(std::vector<int>& lvalue) {
  35.     for (auto i : reverse(lvalue)) {
  36.         foo(i);
  37.     }
  38. }
  39.  
  40.  
  41. void test_rvalue() {
  42.     for (auto i : reverse(make_vec())) {
  43.         foo(i);
  44.     }
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top