Advertisement
homer512

visitor

Jan 22nd, 2014
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class Base;
  7. class A;
  8. struct BaseVisitor
  9. {
  10.   virtual void visit (Base&) = 0;
  11.   virtual void visit (A&) = 0;
  12. };
  13. struct Base {
  14.   int av;
  15.   virtual void accept (BaseVisitor& v) {
  16.     v.visit (*this);
  17.   }
  18. };
  19.  
  20. struct A : public Base {
  21.   int bv;
  22.   virtual void accept (BaseVisitor& v) {
  23.     v.visit (*this);
  24.   }
  25. };
  26.  
  27. struct ValueFinder: public BaseVisitor {
  28.   int value;
  29.   bool found;
  30.   ValueFinder (int value) : value(value) {}
  31.   virtual void visit (Base& b) {
  32.     found = value == b.av;
  33.   }
  34.   virtual void visit (A& b) {
  35.     found = value == b.bv;
  36.   }
  37. };
  38.  
  39. struct database {
  40.   vector <Base*> basev;
  41.   Base NBase;
  42.    
  43.   database () { NBase.av = 0; }
  44.    
  45.   Base* findb (int value) {
  46.     ValueFinder finder(value);
  47.     for (int i = 0; i < basev.size (); ++i) {
  48.       basev[i]->accept (finder);
  49.       if(finder.found)
  50.     return basev[i];
  51.     }
  52.     return &NBase;
  53.   }
  54. } db;
  55.    
  56. struct BasePrinter: public BaseVisitor {
  57.   virtual void visit (Base& b) {
  58.     cout << b.av << endl;
  59.   }
  60.   virtual void visit (A& b) {
  61.     cout << b.bv << endl;
  62.   }
  63.  
  64. };
  65. int main( ) {
  66.  
  67.   Base der;
  68.   der.av = 5;
  69.   db.basev.push_back (&der);
  70.  
  71.   Base* found = db.findb (5);
  72.   BasePrinter printer;
  73.   found->accept(printer);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement