1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. struct iteratable {
  6. virtual ~iteratable() {}
  7.  
  8. virtual const bool has_next() = 0;
  9. virtual void next() = 0;
  10. virtual const T get_value() = 0;
  11. };
  12.  
  13. template <typename Iterator>
  14. struct aggregatable {
  15. virtual ~aggregatable() {}
  16. virtual Iterator iterator_begin() = 0;
  17. };
  18.  
  19. template <typename T, typename List>
  20. class element_iterator : public iteratable<T> {
  21. const List &list_;
  22. size_t index_;
  23.  
  24. public :
  25. element_iterator(const List &list) : list_(list), index_(0) {}
  26.  
  27. const bool has_next() {
  28. return (list_.get_last_num() > index_) ? true : false;
  29. }
  30.  
  31. void next() { ++index_; }
  32.  
  33. const T get_value() { return list_.get_value_at(index_); }
  34. };
  35.  
  36. template <typename T>
  37. class element_list : public aggregatable<element_iterator<T, element_list<T> > > {
  38. T *plist_;
  39. size_t last_;
  40.  
  41. public :
  42. typedef element_iterator<T, element_list<T> > iterator;
  43.  
  44. element_list(const size_t count) : plist_(new T[count]), last_(0) {
  45. }
  46.  
  47. ~element_list() {
  48. delete [] plist_;
  49. }
  50.  
  51. void add(const T val) {
  52. plist_[last_++] = val;
  53. }
  54.  
  55. const T get_value_at(const size_t index) const {
  56. return plist_[index];
  57. }
  58.  
  59. const size_t get_last_num() const {
  60. return last_;
  61. }
  62.  
  63. element_iterator<T, element_list<T>> iterator_begin() {
  64. return element_iterator<T, element_list<T> >(*this);
  65. }
  66. };
  67.  
  68. int main() {
  69. element_list<int> list(5);
  70.  
  71. for (int i = 0; i < 5; ++i) {
  72. list.add(i);
  73. }
  74.  
  75. element_list<int>::iterator it = list.iterator_begin();
  76. for ( it; it.has_next(); it.next()) {
  77. cout << it.get_value() << endl;
  78. }
  79. }
  80.  
最終更新:2008年09月10日 21:27