-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.h
105 lines (89 loc) · 2.42 KB
/
utility.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
#ifndef UTILITY_H_
#define UTILITY_H_
#include <charconv>
#include <optional>
#include <string>
#if defined(__GNUC__) && not defined(__clang__) || defined(_MSC_VER)
#else
#include <stdexcept>
#endif
template<typename T>
std::optional<T> optional_parse(const std::string &str);
template<>
std::optional<int> optional_parse(const std::string &str) {
int val;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), val);
if (ec == std::errc {}) {
return std::nullopt;
}
return val;
}
template<>
std::optional<std::uint64_t> optional_parse(const std::string &str) {
std::uint64_t val;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), val);
if (ec == std::errc {}) {
return std::nullopt;
}
return val;
}
// GCC and MSVC support floating point std::from_chars
#if defined(__GNUC__) && not defined(__clang__) || defined(_MSC_VER)
template<>
std::optional<float> optional_parse(const std::string &str) {
float val;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), val, std::chars_format::general);
if (ec == std::errc {}) {
return std::nullopt;
}
return val;
}
template<>
std::optional<double> optional_parse(const std::string &str) {
double val;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), val, std::chars_format::general);
if (ec == std::errc {}) {
return std::nullopt;
}
return val;
}
template<>
std::optional<long double> optional_parse(const std::string &str) {
long double val;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), val, std::chars_format::general);
if (ec == std::errc {}) {
return std::nullopt;
}
return val;
}
// Clang doesn't support floating point std::from_chars which is a part of C++17. Good job, Clang!
#else
template<>
std::optional<float> optional_parse(const std::string &str) {
try {
return std::stof(str);
}
catch (std::logic_error &e) {
return std::nullopt;
}
}
template<>
std::optional<double> optional_parse(const std::string &str) {
try {
return std::stod(str);
}
catch (std::logic_error &e) {
return std::nullopt;
}
}
template<>
std::optional<long double> optional_parse(const std::string &str) {
try {
return std::stold(str);
}
catch (std::logic_error &e) {
return std::nullopt;
}
}
#endif
#endif