The Battle for Wesnoth  1.15.3+dev
conversion_helper.hpp
Go to the documentation of this file.
1 //
2 // M A R I A D B + +
3 //
4 // Copyright The ViaDuck Project 2016 - 2018.
5 // Distributed under the Boost Software License, Version 1.0.
6 // (See accompanying file LICENSE or copy at
7 // http://www.boost.org/LICENSE_1_0.txt)
8 
9 #ifndef MARIADBCLIENTPP_CONVERSION_HELPER_H
10 #define MARIADBCLIENTPP_CONVERSION_HELPER_H
11 
12 #include <limits>
13 #include <stdexcept>
14 
15 #ifdef WIN32
16 #undef max
17 #undef min
18 #endif
19 
20 template <typename T, typename K>
21 inline T checked_cast(K value) {
22  if (value < std::numeric_limits<T>::lowest() || value > std::numeric_limits<T>::max()) return T();
23 
24  return static_cast<T>(value);
25 }
26 
27 template <typename T>
28 inline T string_cast(const std::string &str) {
29  size_t endPos;
30  int parsedNumber = std::stoi(str, &endPos);
31 
32  if (endPos != str.size()) return T();
33 
34  return checked_cast<T>(parsedNumber);
35 }
36 
37 template <>
38 inline unsigned long string_cast(const std::string &str) {
39  size_t endPos;
40  unsigned long parsedNumber = std::stoul(str, &endPos);
41 
42  if (endPos != str.size()) return 0;
43 
44  return parsedNumber;
45 }
46 
47 template <>
48 inline unsigned int string_cast(const std::string &str) {
49  unsigned long parsedNumber = string_cast<unsigned long>(str);
50 
51  return checked_cast<unsigned int>(parsedNumber);
52 }
53 
54 template <>
55 inline unsigned long long string_cast(const std::string &str) {
56  size_t endPos;
57  unsigned long long parsedNumber = std::stoull(str, &endPos);
58 
59  if (endPos != str.size()) return 0;
60 
61  return parsedNumber;
62 }
63 
64 template <>
65 inline long long string_cast(const std::string &str) {
66  size_t endPos;
67  long long parsedNumber = std::stoll(str, &endPos);
68 
69  if (endPos != str.size()) return 0;
70 
71  return parsedNumber;
72 }
73 
74 template <>
75 inline double string_cast(const std::string &str) {
76  size_t endPos;
77  try {
78  double parsedNumber = std::stod(str, &endPos);
79 
80  if (endPos != str.size()) return 0;
81 
82  return parsedNumber;
83  } catch (std::out_of_range &) {
84  // Not a Number double
85  return std::numeric_limits<double>::quiet_NaN();
86  }
87 }
88 
89 template <>
90 inline float string_cast(const std::string &str) {
91  size_t endPos;
92  try {
93  float parsedNumber = std::stof(str, &endPos);
94 
95  if (endPos != str.size()) return 0;
96 
97  return parsedNumber;
98  } catch (std::out_of_range &) {
99  // Not a Number float
100  return std::numeric_limits<float>::quiet_NaN();
101  }
102 }
103 
104 #endif // MARIADBCLIENTPP_CONVERSION_HELPER_H
std::string str
Definition: statement.cpp:110
T string_cast(const std::string &str)
T checked_cast(K value)