-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.h
108 lines (77 loc) · 2.06 KB
/
template.h
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
100
101
102
103
104
105
106
107
108
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <initializer_list>
#include <stdexcept>
#include <type_traits>
#include <utility> // std::pair
#include <vector>
class TemplateError : std::exception {
private:
const std::string m_Message;
public:
TemplateError(const std::string &msg);
~TemplateError() throw();
const char *what() const throw();
};
class VariableProvider {
public:
virtual void handle_variable(std::ostream &out,
const std::string &name) = 0;
};
class EmptyVariableProvider : public VariableProvider {
public:
void handle_variable(std::ostream &out, const std::string &name);
};
template<typename Map>
class MapVariableProvider : public VariableProvider {
private:
const Map &m_Map;
public:
MapVariableProvider(const Map &map)
: m_Map(map)
{
}
void handle_variable(std::ostream &out, const std::string &name)
{
try {
out << m_Map.at(name);
}
catch(std::out_of_range &e)
{
throw TemplateError("Missing value for variable " + name);
}
}
};
class Template {
public:
enum BlockType {
DATA,
VARIABLE
};
typedef std::pair<BlockType, std::string> Block;
protected:
std::vector<Block> m_Blocks;
static bool is_space(char c);
public:
Template(const std::string &filename);
Template(std::istream &source, const std::string &filename = "<stream>");
virtual ~Template();
void compile(std::istream &source, const std::string &filename);
template<typename Map>
typename std::enable_if<
!std::is_base_of<VariableProvider, Map>::value,
void>::type
render(std::ostream &out, const Map &map)
{
MapVariableProvider<Map> wrapper(map);
render(out, wrapper);
}
void render(std::ostream &out, VariableProvider &vars);
void render(std::ostream &out, std::initializer_list<const char*> vars);
inline void render(std::ostream &out)
{
EmptyVariableProvider empty;
render(out, empty);
}
};
#endif