NSVD Reader  0.0.1
to_int.hpp
Go to the documentation of this file.
1 
5 /*
6  * These codes are licensed under CC0.
7  * http://creativecommons.org/publicdomain/zero/1.0/
8  */
9 
10 #ifndef __NODAMUSHI_TO_INT_HPP__
11 #define __NODAMUSHI_TO_INT_HPP__
12 
13 # include <cstdint>
14 # include <string>
15 # if __cplusplus >= 201703
16 # include <string_view>
17 # include <optional>
18 # include <charconv>
19 # else
20 # include <type_traits>
21 # endif
22 
23 
24 namespace nodamushi{
25 # if __cplusplus >= 201703
26 template<typename INT>
27 INT to_int(std::string_view v,int base=10)
28 {
29  INT x;
30  std::from_chars(v.data(), v.data()+v.length(),x,base);
31  return x;
32 }
33 template<typename INT>
34 INT to_int(std::string_view v,size_t begin,size_t end,int base=10)
35 {
36  INT x;
37  std::from_chars(v.data()+begin, v.data()+end,x,base);
38  return x;
39 }
40 template<typename INT>
41 INT to_int(const char* text,size_t begin,size_t end,int base=10)
42 {
43  INT x;
44  std::from_chars(text+begin, text+end,x,base);
45  return x;
46 }
47 template<typename INT>
48 INT to_int(const char* text,int base=10)
49 {
50  INT x;
51  const char* end=text;
52  while(*text)text++;
53  std::from_chars(text,end,x,base);
54  return x;
55 }
56 
57 
58 # else
59 
60 namespace details{
61 template<bool> struct _to_int;
62 
63 template<> struct _to_int<true>
64 {
65  static unsigned long long conv(const std::string& v,int base=10)
66  {
67  return ::std::stoull(v,nullptr,base);
68  }
69 };
70 template<> struct _to_int<false>
71 {
72  static long long conv(const std::string& v,int base=10)
73  {
74  return ::std::stoll(v,nullptr,base);
75  }
76 };
77 }
78 
79 template<typename INT>
80 INT to_int(const std::string& v,int base=10)
81 {
82  constexpr bool unsig = std::is_unsigned<INT>::value;
83  return static_cast<INT>(details::_to_int<unsig>::conv(v,base));
84 }
85 
86 template<typename INT>
87 INT to_int(const std::string& v,size_t begin,size_t end,int base=10)
88 {
89  std::string s = v.substr(begin,end-begin);
90  return to_int<INT>(s,base);
91 }
92 template<typename INT>
93 INT to_int(const char* text,size_t begin,size_t end,int base=10)
94 {
95  std::string s(text+begin,text+end);
96  return to_int<INT>(s,base);
97 }
98 template<typename INT>
99 INT to_int(const char* text,int base=10)
100 {
101  const std::string s = text;
102  return to_int<INT>(s,base);
103 }
104 
105 # endif
106 
107 
108 }// end namespace nodamushi
109 
110 #endif // __TO_INT_HPP__
static unsigned long long conv(const std::string &v, int base=10)
Definition: to_int.hpp:65
INT to_int(const std::string &v, int base=10)
Definition: to_int.hpp:80
static long long conv(const std::string &v, int base=10)
Definition: to_int.hpp:72