-
Notifications
You must be signed in to change notification settings - Fork 0
/
visitor.cpp
60 lines (49 loc) · 1.59 KB
/
visitor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <memory>
class Visitable1;
class Visitable2;
class BaseVisitable;
class BaseVisitor {
public:
virtual int visit(BaseVisitable &c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual int visit(Visitable1 &c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual int visit(Visitable2 &c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual ~BaseVisitor()= default;
};
class Visitor1 : public BaseVisitor{
public:
int visit(Visitable1 &c) override { std::cout << __PRETTY_FUNCTION__ << std::endl; }
int visit(Visitable2 &c) override { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
class Visitor2 : public BaseVisitor{
public:
int visit(Visitable2 &c) override { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
/*************************************************************************/
class BaseVisitable {
public:
virtual ~BaseVisitable()= default;
virtual int accept(BaseVisitor *v) { return v->visit(*this); }
};
class Visitable1 : public BaseVisitable {
/* Visitable accept one BaseVisitor */
public:
int accept(BaseVisitor *v) { return v->visit(*this); }
};
class Visitable2 : public BaseVisitable {
/* Visitable accept one BaseVisitor */
public:
int accept(BaseVisitor *v) { return v->visit(*this); }
};
int main(int argc, char **argv) {
Visitor1 visitor1;
Visitor2 visitor2;
Visitable1 visitable1;
Visitable2 visitable2;
BaseVisitable *visitable = &visitable1;
visitable->accept(&visitor1);
visitable->accept(&visitor2);
visitable = &visitable2;
visitable->accept(&visitor1);
visitable->accept(&visitor2);
}