fork download
  1. #include <algorithm>
  2. #include <functional>
  3. #include <iostream>
  4. #include <vector>
  5. #include <iterator>
  6.  
  7. struct Foo
  8. {
  9. int value;
  10. Foo(int value) : value(value){};
  11. };
  12.  
  13. struct Bar
  14. {
  15. std::vector<Foo> values;
  16. size_t size_foo() const {return values.size();}
  17. Foo& get_foo(size_t index) {return values[index];}
  18. };
  19.  
  20. template <typename TOuter, typename TInner> struct ContainerProxy;
  21.  
  22. template <typename TOuter, typename TInner>
  23. struct ContainerIterator : public std::iterator<std::input_iterator_tag, TInner>
  24. {
  25. typedef std::function<TInner& (TOuter*, size_t)> getfunc_type;
  26. TOuter& mContainerRef;
  27. size_t mIndex;
  28. getfunc_type mGetfunc;
  29.  
  30. ContainerIterator(TOuter& containerRef, size_t index, getfunc_type const& getFunc)
  31. : mContainerRef(containerRef), mIndex(index), mGetfunc(getFunc)
  32. {
  33. }
  34.  
  35. TInner& operator*() {return mGetfunc(&mContainerRef, mIndex);}
  36. ContainerIterator<TOuter, TInner>& operator++() {++mIndex; return *this;}
  37.  
  38. bool operator==(ContainerIterator<TOuter, TInner> const& rhs) const
  39. {
  40. return &mContainerRef==&rhs.mContainerRef &&
  41. mIndex==rhs.mIndex;
  42. }
  43.  
  44. bool operator!=(ContainerIterator<TOuter, TInner> const& rhs) const
  45. {
  46. return !operator==(rhs);
  47. }
  48. };
  49.  
  50. template <typename TOuter, typename TInner>
  51. struct ContainerProxy
  52. {
  53. TOuter& mContainerRef;
  54.  
  55. typedef std::function<size_t (TOuter*)> sizefunc_type;
  56. sizefunc_type mSizefunc;
  57.  
  58. typedef std::function<TInner& (TOuter*, size_t)> getfunc_type;
  59. getfunc_type mGetfunc;
  60.  
  61.  
  62. ContainerProxy(TOuter& containerRef, sizefunc_type sizefunc, getfunc_type getfunc) :
  63. mContainerRef(containerRef), mSizefunc(sizefunc), mGetfunc(getfunc)
  64. {
  65. }
  66.  
  67. ContainerIterator<TOuter, TInner> begin() const
  68. {
  69. return ContainerIterator<TOuter, TInner>(mContainerRef, 0, mGetfunc);
  70. }
  71.  
  72. ContainerIterator<TOuter, TInner> end() const
  73. {
  74. return ContainerIterator<TOuter, TInner>(mContainerRef, mSizefunc(&mContainerRef), mGetfunc);
  75. }
  76. };
  77.  
  78.  
  79. int main()
  80. {
  81. Bar b;
  82. b.values.push_back(Foo(1));
  83. b.values.push_back(Foo(2));
  84.  
  85. ContainerProxy<Bar, Foo> proxy(b, &Bar::size_foo, &Bar::get_foo);
  86.  
  87. std::for_each(proxy.begin(), proxy.end(), [](Foo& f) {std::cout<<f.value<<std::endl;});
  88. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
1
2