Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- class Base;
- class A;
- struct BaseVisitor
- {
- virtual void visit (Base&) = 0;
- virtual void visit (A&) = 0;
- };
- struct Base {
- int av;
- virtual void accept (BaseVisitor& v) {
- v.visit (*this);
- }
- };
- struct A : public Base {
- int bv;
- virtual void accept (BaseVisitor& v) {
- v.visit (*this);
- }
- };
- struct ValueFinder: public BaseVisitor {
- int value;
- bool found;
- ValueFinder (int value) : value(value) {}
- virtual void visit (Base& b) {
- found = value == b.av;
- }
- virtual void visit (A& b) {
- found = value == b.bv;
- }
- };
- struct database {
- vector <Base*> basev;
- Base NBase;
- database () { NBase.av = 0; }
- Base* findb (int value) {
- ValueFinder finder(value);
- for (int i = 0; i < basev.size (); ++i) {
- basev[i]->accept (finder);
- if(finder.found)
- return basev[i];
- }
- return &NBase;
- }
- } db;
- struct BasePrinter: public BaseVisitor {
- virtual void visit (Base& b) {
- cout << b.av << endl;
- }
- virtual void visit (A& b) {
- cout << b.bv << endl;
- }
- };
- int main( ) {
- Base der;
- der.av = 5;
- db.basev.push_back (&der);
- Base* found = db.findb (5);
- BasePrinter printer;
- found->accept(printer);
- }
Advertisement
Add Comment
Please, Sign In to add comment