-
Notifications
You must be signed in to change notification settings - Fork 1
/
groovy_style_builder.cpp
99 lines (81 loc) · 1.84 KB
/
groovy_style_builder.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/***
Acknowledagement: This is a lecture note for course https://www.udemy.com/course/patterns-cplusplus/ by
@Dmitri Nesteruk
Title: Groovy-Style Builder
A lot take away from the code could be found in the lecture notes
Shiyu Mou
***/
#include <string>
#include <vector>
#include <iostream>
namespace html {
struct Tag
{
std::string name;
std::string text;
std::vector<Tag> children;
std::vector<std::pair<std::string, std::string>> attributes;
// operator << for directly print object
friend std::ostream& operator<<(std::ostream& os, const Tag& tag)
{
os << "<" << tag.name;
for (const auto& att : tag.attributes)
os << " " << att.first << "=\"" << att.second << "\"";
if (tag.children.size() == 0 && tag.text.length() == 0)
{
os << "/>" << std::endl;
}
else
{
os << ">" << std::endl;
if (tag.text.length())
os << tag.text << std::endl;
for (const auto& child : tag.children)
os << child;
os << "</" << tag.name << ">" << std::endl;
}
return os;
}
protected:
Tag(const std::string& name, const std::string& text)
: name{name},
text{text}
{
}
Tag(const std::string& name, const std::vector<Tag>& children)
: name{name},
children{children}
{
}
};
struct P : Tag
{
explicit P(const std::string& text)
: Tag{"p", text}
{
}
P(std::initializer_list<Tag> children)
: Tag("p", children)
{
}
};
struct IMG : Tag
{
explicit IMG(const std::string& url)
: Tag{"img", ""}
{
attributes.emplace_back(make_pair("src", url));
}
};
}
int main1()
{
using namespace html;
std::cout <<
P {
IMG {"http://pokemon.com/pikachu.png"}
}
<< std::endl;
getchar();
return 0;
}