-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEnums.h
116 lines (86 loc) · 1.53 KB
/
Enums.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
109
110
111
112
113
114
115
116
/*
* Enums.h
*
* Created on: 29 Sep 2016
* Author: jeremy
*/
#ifndef SOURCE_UTIL_ENUMS_H_
#define SOURCE_UTIL_ENUMS_H_
#include "ErrorHandling.h"
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
namespace Util
{
/**
* Helper function to make conversion to enums easier.
* @param is Input stream.
* @param x Enum type to convert the input stream to.
* @return
*/
template <typename T>
inline std::istream& StreamToEnum(std::istream& is, T& x)
{
std::string s;
is >> s;
for(const auto& l : T())
{
std::ostringstream os;
os << l;
if(os.str() == s)
{
x = l;
}
}
return is;
}
class Enums
{
public:
template<typename T>
static std::string ToString(const T& e)
{
for (const auto& c : T{})
{
if(c == e)
{
std::stringstream ss;
ss << e;
return ss.str();
}
}
throw Exception("Could not convert enum to string.", error_type_error);
return "";
}
template<typename T>
static T ToElement(const std::string& s)
{
for (const auto& c : T{})
{
std::stringstream ss;
ss << c;
if(ss.str() == s)
{
return c;
}
}
throw Exception("Could not convert string " + s + " to enum.", error_type_error);
return T::First;
}
template<typename T>
static std::vector<T> GetEnumVector()
{
std::vector<T> v;
for (const auto& c : T{})
{
v.push_back(c);
}
return v;
}
private:
Enums() = delete;
~Enums() = delete;
};
}
#endif /* SOURCE_UTIL_ENUMS_H_ */