Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- #include <utility>
- using namespace std;
- struct Base;
- struct A;
- struct B;
- struct Visitor {
- virtual void visit (Base& b) = 0;
- virtual void visit (A& a) = 0;
- virtual void visit (B& b) = 0;
- };
- struct Base {
- int av;
- virtual void accept (Visitor& v) { v.visit (*this); }
- template <class VisitorType, class... Params>
- VisitorType accept (Params... args)
- {
- VisitorType v (forward <Params> (args)...);
- this->accept (v);
- return v;
- }
- Base () { av = 1;}
- };
- struct A : public Base {
- int bv;
- void accept (Visitor& v) { v.visit (*this); }
- A () { av = 2; bv = 3; }
- };
- struct B : public Base {
- string cv;
- void accept (Visitor& v) { v.visit (*this); }
- B () { av = 4; cv = "s5"; }
- };
- struct Print : Visitor {
- void visit (Base& b) { cout << "av " << b.av << endl; }
- void visit (A& b) { cout << "bv " << b.bv << endl; }
- void visit (B& b) { cout << "cv " << b.cv << endl; }
- };
- struct Add : Visitor {
- int av, bv;
- Add (int av, int bv)
- : av (av), bv (bv)
- {}
- void visit (Base& b) { av += b.av; }
- void visit (A& b) { av += b.av; bv += b.bv; }
- void visit (B& b) { av += b.av; }
- };
- struct data {
- vector <Base*> basev;
- Base* findb (int value) {
- static Base base; Base* pBase = &base;
- for (int i = 0; i < basev.size (); ++i) {
- if (basev[i]->av == value) return basev[i];
- }
- return pBase;
- }
- } d;
- int main() {
- d.basev.push_back (new Base);
- d.basev.push_back (new A);
- d.basev.push_back (new B);
- Base* found = d.findb (4);
- found->accept <Print> ();
- int av = found->accept <Add> (0, 0).av;
- cout << av << "\n" << "\nDone\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment