fork download
  1. #include <iostream>
  2. #include <cassert>
  3.  
  4. template<class T, char STEP = 1>
  5. class simple_container
  6. {
  7. class simple_iterator;
  8. public:
  9. simple_container(const T &val) : _value(val)
  10. {
  11. if (std::abs(STEP) != 1 && std::abs(STEP) != 2)
  12. {
  13. assert(STEP % 4 == 0);
  14. assert(STEP != 0);
  15. }
  16.  
  17. }
  18.  
  19. simple_iterator begin()
  20. {
  21. return (STEP > 0 ? simple_iterator(_value, STEP, 0) : simple_iterator(_value, STEP, static_cast<long>(sizeof (T) * 8) + STEP));
  22.  
  23. }
  24. simple_iterator end()
  25. {
  26. return (STEP > 0 ? simple_iterator(_value, STEP, sizeof (T) * 8) : simple_iterator(_value, STEP, STEP));
  27. }
  28. private:
  29. class simple_iterator
  30. {
  31. public:
  32. bool operator!=(const simple_iterator&l)
  33. {
  34. return (_info.pos != l._info.pos) ||
  35. (_info.step != l._info.step) ||
  36. (_val != l._val);
  37. }
  38. unsigned char operator*()
  39. {
  40. return static_cast<unsigned char>((_val >> _info.pos) & (~(0xFF << (_info.step > 0 ? _info.step : -_info.step))));
  41. }
  42.  
  43. simple_iterator& operator++()
  44. {
  45. _info.pos += _info.step;
  46. return *this;
  47. }
  48. private:
  49. friend class simple_container;
  50.  
  51. simple_iterator(const T &val, char step, long pos)
  52. : _info{pos, step}, _val(val) {}
  53.  
  54. struct _info_data
  55. {
  56. long pos;
  57. char step;
  58. };
  59. _info_data _info;
  60. const T &_val;
  61.  
  62. };
  63. const T &_value;
  64. };
  65.  
  66. int main() {
  67. unsigned char val = 0b11111001;
  68. simple_container<unsigned char, 1> v(val);
  69. for(auto el : v)
  70. std::cout << std::hex<< static_cast<int>(el);
  71. std::cout << std::endl;
  72.  
  73.  
  74. simple_container<unsigned char, -1> rv(val);
  75. for(auto el : rv)
  76. std::cout << std::hex<< static_cast<int>(el);
  77. std::cout << std::endl;
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0s 4576KB
stdin
Standard input is empty
stdout
10011111
11111001