-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrong_shared_ptr_visitor.cpp
60 lines (49 loc) · 1.88 KB
/
wrong_shared_ptr_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(std::shared_ptr<BaseVisitable> c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual int visit(std::shared_ptr<Visitable1> c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual int visit(std::shared_ptr<Visitable2> c) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual ~BaseVisitor()= default;
};
class Visitor1 : public BaseVisitor{
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:
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(shared_from_this()); }
};
class Visitable1 : public BaseVisitable {
/* Visitable accept one BaseVisitor */
public:
int accept(BaseVisitor *v) { return v->visit(shared_from_this()); }
};
class Visitable2 : public BaseVisitable {
/* Visitable accept one BaseVisitor */
public:
int accept(BaseVisitor *v) { return v->visit(shared_from_this()); }
};
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);
}