-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreflective_visitor.cpp
More file actions
82 lines (69 loc) · 1.79 KB
/
Copy pathreflective_visitor.cpp
File metadata and controls
82 lines (69 loc) · 1.79 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
// visitor examples for design patterns c++ book
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
/**
* Hierarchy of mathematical operations.
*
* We would like to add printing behavior.
*/
struct Expression {
virtual ~Expression() = default;
};
struct DoubleExpression : Expression {
double value;
explicit DoubleExpression(const double value) : value{value} {}
};
struct AdditionExpression : Expression {
Expression *left, *right;
AdditionExpression(Expression *const left, Expression *const right)
: left{left}, right{right} {}
~AdditionExpression() {
delete left;
delete right;
}
};
// Printer machine is external! GOOD
// But sequence of if-else + dynamic_cast cannot be avoided.
struct ExpressionPrinter {
// THIS CANNOT BE IMPLEMENTED, AS WE DO NOT KNOW THE TYPE OF THE EXPRESSION AT
// COMPILE TIME!
//
// void print(DoubleExpression *de, ostringstream &oss) const {
// oss << de->value;
// }
// void print(AdditionExpression *ae, ostringstream &oss) const {
// oss << "(";
// print(ae->left, oss);
// oss << "+";
// print(ae->right, oss);
// oss << ")";
// }
ostringstream oss;
void print(Expression *e) {
if (auto de = dynamic_cast<DoubleExpression *>(e)) {
oss << de->value;
} else if (auto ae = dynamic_cast<AdditionExpression *>(e)) {
oss << "(";
print(ae->left);
oss << "+";
print(ae->right);
oss << ")";
}
}
string str() const { return oss.str(); }
};
int main() {
// 1 + 2 + 3
// __+__
// 1 _+_
// 2 3
//
auto e = new AdditionExpression{
new DoubleExpression{1},
new AdditionExpression{new DoubleExpression{2}, new DoubleExpression{3}}};
ExpressionPrinter ep;
ep.print(e);
cout << ep.str() << endl;
}