]> granicus.if.org Git - icinga2/blob - lib/base/convert.hpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / convert.hpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #ifndef CONVERT_H
4 #define CONVERT_H
5
6 #include "base/i2-base.hpp"
7 #include "base/value.hpp"
8 #include <boost/lexical_cast.hpp>
9
10 namespace icinga
11 {
12
13 /**
14  * Utility class for converting types.
15  *
16  * @ingroup base
17  */
18 class Convert
19 {
20 public:
21         template<typename T>
22         static long ToLong(const T& val)
23         {
24                 try {
25                         return boost::lexical_cast<long>(val);
26                 } catch (const std::exception&) {
27                         std::ostringstream msgbuf;
28                         msgbuf << "Can't convert '" << val << "' to an integer.";
29                         BOOST_THROW_EXCEPTION(std::invalid_argument(msgbuf.str()));
30                 }
31         }
32
33         template<typename T>
34         static double ToDouble(const T& val)
35         {
36                 try {
37                         return boost::lexical_cast<double>(val);
38                 } catch (const std::exception&) {
39                         std::ostringstream msgbuf;
40                         msgbuf << "Can't convert '" << val << "' to a floating point number.";
41                         BOOST_THROW_EXCEPTION(std::invalid_argument(msgbuf.str()));
42                 }
43         }
44
45         static long ToLong(const Value& val)
46         {
47                 return val;
48         }
49
50         static long ToLong(double val)
51         {
52                 return static_cast<long>(val);
53         }
54
55         static double ToDouble(const Value& val)
56         {
57                 return val;
58         }
59
60         static bool ToBool(const Value& val)
61         {
62                 return val.ToBool();
63         }
64
65         template<typename T>
66         static String ToString(const T& val)
67         {
68                 return boost::lexical_cast<std::string>(val);
69         }
70
71         static String ToString(const String& val);
72         static String ToString(const Value& val);
73         static String ToString(double val);
74
75         static double ToDateTimeValue(double val);
76         static double ToDateTimeValue(const Value& val);
77
78 private:
79         Convert();
80 };
81
82 }
83
84 #endif /* CONVERT_H */