-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathintrusive_visitor.cpp
More file actions
63 lines (52 loc) · 1.28 KB
/
Copy pathintrusive_visitor.cpp
File metadata and controls
63 lines (52 loc) · 1.28 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
// 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;
// intrusive implementation!.
virtual void print(ostringstream &oss) = 0;
};
struct DoubleExpression : Expression {
double value;
explicit DoubleExpression(const double value) : value{value} {}
// intrusive implementation.!
void print(ostringstream &oss) override { oss << value; }
};
struct AdditionExpression : Expression {
Expression *left, *right;
AdditionExpression(Expression *const left, Expression *const right)
: left{left}, right{right} {}
~AdditionExpression() {
delete left;
delete right;
}
// intrusive implementation!.
void print(ostringstream &oss) override {
oss << "(";
left->print(oss);
oss << "+";
right->print(oss);
oss << ")";
}
};
int main() {
// 1 + 2 + 3
// __+__
// 1 _+_
// 2 3
//
auto e = new AdditionExpression{
new DoubleExpression{1},
new AdditionExpression{new DoubleExpression{2}, new DoubleExpression{3}}};
ostringstream oss;
e->print(oss);
cout << oss.str() << endl;
return 0;
}