-
Notifications
You must be signed in to change notification settings - Fork 0
/
visitor_visitable_clean.cpp
70 lines (57 loc) · 2.04 KB
/
visitor_visitable_clean.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
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <memory>
class Visitable1;
class Visitable2;
class BaseVisitable;
class BaseVisitor {
public:
virtual int visit(std::shared_ptr<BaseVisitable> c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual ~BaseVisitor()= default;
};
template<class T> class Visitor{
public:
virtual int visit(std::shared_ptr<T> c){ std::cout << __PRETTY_FUNCTION__ << std::endl;}
};
class Visitor1 : public BaseVisitor, public Visitor<Visitable1>, public Visitor<Visitable2>{
public:
int visit(std::shared_ptr<Visitable1> c) override { std::cout << __PRETTY_FUNCTION__ << std::endl; }
int visit(std::shared_ptr<Visitable2> c) override { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
class Visitor2 : public BaseVisitor, public Visitor<Visitable2>{
public:
int visit(std::shared_ptr<Visitable2> c) override { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
/*************************************************************************/
class BaseVisitable : public std::enable_shared_from_this<BaseVisitable> {
public:
virtual ~BaseVisitable()= default;
virtual int accept(BaseVisitor *v) { return v->visit(std::static_pointer_cast<BaseVisitable>(shared_from_this())); }
};
template<class T>
class Visitable: public BaseVisitable{
public:
int accept(BaseVisitor *v) {
if (Visitor<T> *p = dynamic_cast<Visitor<T> *>(v))
return p->visit(std::static_pointer_cast<T>(shared_from_this()));
}
};
class Visitable1 : public Visitable<Visitable1> {
/* Visitable accept one BaseVisitor */
public:
};
class Visitable2 : public Visitable<Visitable2> {
/* Visitable accept one BaseVisitor */
public:
};
int main(int argc, char **argv) {
Visitor1 visitor1;
Visitor2 visitor2;
std::shared_ptr<Visitable1> visitable1 = std::make_shared<Visitable1>();
std::shared_ptr<Visitable2> visitable2 = std::make_shared<Visitable2>();
std::shared_ptr<BaseVisitable> visitable = visitable1;
visitable->accept(&visitor1);
visitable->accept(&visitor2);
visitable = visitable2;
visitable->accept(&visitor1);
visitable->accept(&visitor2);
}