#include using namespace std; template class Stat { public: virtual void apply(T &) = 0; }; template class Printer : public Stat { public: virtual void apply(T & v) { cout << v << ' '; } }; template class Counter : public Stat { int l; public: Counter() : l(0) {} virtual void apply(T & v) { l++; } int getL()const { return l; } }; template struct Elem { T inf; Elem * next; }; template class List { public: List(); ~List(); void add(const T &); void removeFirst(); void iterate(Stat &); bool isEmpty() const; private: Elem * start; List(const List&); List& operator=(const List &); }; template List::List() { start = NULL; } template void List::add(const T & v) { Elem * n = new Elem; n->inf = v; n->next = start; start = n; } template void List::removeFirst() { Elem * n = start; start = n->next; delete n; } template bool List::isEmpty() const { return start == NULL; } template void List::iterate(Stat & s) { Elem * t = start; while(t != NULL) { s.apply(t->inf); t = t->next; } } template List::~List(){ while( !isEmpty() ) { removeFirst(); } } template class Applier : public Stat< Stat * > { T v; public: Applier(const T & _v) : v(_v) {} virtual void apply( Stat * & s) { s->apply(v); } }; template class CompositStat : public Stat { List< Stat * > l; public: void apply(T & v) { Applier a(v); l.iterate(a); } void add(Stat * s) { l.add(s); } }; int main() { List a; a.add(5); for ( int i = 0; i < 10; ++i ) { a.add(i); } Printer p; Counter c; CompositStat cs; cs.add(&c); cs.add(&p); a.iterate(cs); cout << endl; cout << c.getL() << endl; return 0; }