JayBeams  0.1
Another project to have fun coding.
strtonum.hpp
Go to the documentation of this file.
1 #ifndef jb_strtonum_hpp
2 #define jb_strtonum_hpp
3 
4 #include <stdexcept>
5 #include <string>
6 
7 namespace jb {
8 
9 /**
10  * Traits to convert strings to numbers (e.g. integers, floats, etc).
11  *
12  * For most types this refactors repetitive code, but also allows
13  * specialization for specific types.
14  */
15 template <typename T>
16 struct stn_traits;
17 
18 #define STN_TRAITS(T, F) \
19  template <> \
20  struct stn_traits<T> { \
21  static T stot(std::string const& s, std::size_t& end) { \
22  return (F)(s, &end); \
23  } \
24  }
25 
26 STN_TRAITS(int, std::stoi);
27 STN_TRAITS(unsigned long long, std::stoull);
28 STN_TRAITS(long long, std::stoll);
29 STN_TRAITS(unsigned long, std::stoul);
30 STN_TRAITS(long, std::stol);
31 STN_TRAITS(float, std::stof);
32 STN_TRAITS(double, std::stod);
33 
34 #undef STN_TRAITS
35 
36 /**
37  * Generic string to number conversion with validation.
38  */
39 template <typename T>
40 bool strtonum(std::string const& s, T& r) {
41  if (s.empty()) {
42  return false;
43  }
44  try {
45  std::size_t end;
46  T tmp = stn_traits<T>::stot(s, end);
47  if (end != s.length()) {
48  return false;
49  }
50  r = tmp;
51  } catch (std::exception const&) {
52  return false;
53  }
54  return true;
55 }
56 
57 } // namespace jb
58 
59 #endif // jb_strtonum_hpp
STN_TRAITS(int, std::stoi)
bool strtonum(std::string const &s, T &r)
Generic string to number conversion with validation.
Definition: strtonum.hpp:40
Traits to convert strings to numbers (e.g.
Definition: strtonum.hpp:16
The top-level namespace for the JayBeams library.
Definition: as_hhmmss.hpp:7