12 #ifndef SST_CORE_FROM_STRING_H 13 #define SST_CORE_FROM_STRING_H 20 #include <type_traits> 25 std::enable_if_t<std::is_integral_v<T>, T>
26 from_string(
const std::string& input)
28 if constexpr ( std::is_signed_v<T> ) {
29 if constexpr ( std::is_same_v<int, T> ) {
30 return std::stoi(input,
nullptr, 0);
32 else if constexpr ( std::is_same_v<long, T> ) {
33 return std::stol(input,
nullptr, 0);
35 else if constexpr ( std::is_same_v<long long, T> ) {
36 return std::stoll(input,
nullptr, 0);
39 return static_cast<T
>(std::stol(input,
nullptr, 0));
43 if constexpr ( std::is_same_v<bool, T> ) {
45 std::string transform(input);
46 for (
auto& c : transform )
48 if ( transform ==
"true" || transform ==
"t" || transform ==
"yes" || transform ==
"y" ||
49 transform ==
"on" || transform ==
"1" ) {
52 else if ( transform ==
"false" || transform ==
"f" || transform ==
"no" || transform ==
"n" ||
53 transform ==
"off" || transform ==
"0" ) {
57 throw std::invalid_argument(
"from_string: no valid conversion");
60 else if constexpr ( std::is_same_v<unsigned long, T> ) {
61 return std::stoul(input,
nullptr, 0);
63 else if constexpr ( std::is_same_v<unsigned long long, T> ) {
64 return std::stoull(input,
nullptr, 0);
67 return static_cast<T
>(std::stoul(input,
nullptr, 0));
73 std::enable_if_t<std::is_floating_point_v<T>, T>
74 from_string(
const std::string& input)
76 if constexpr ( std::is_same_v<float, T> ) {
79 else if constexpr ( std::is_same_v<double, T> ) {
82 else if constexpr ( std::is_same_v<long double, T> ) {
91 std::enable_if_t<std::is_class_v<T>, T>
92 from_string(
const std::string& input)
94 static_assert(std::is_constructible_v<T, std::string>,
95 "ERROR: from_string can only be used with integral and floating point types and with classes that have a " 96 "constructor that takes a single string as input.\n");
101 std::enable_if_t<std::is_enum_v<T>, T>
102 from_string(
const std::string& input)
104 return static_cast<T
>(from_string<std::underlying_type_t<T>>(input));
110 std::enable_if_t<!std::is_enum_v<T>, std::string>
111 to_string(
const T& input)
113 if constexpr ( std::is_floating_point_v<T> ) {
115 T abs_val = input < 0 ? -input : input;
116 if ( abs_val > (T)10e6 || abs_val < (T)10e-6 )
117 s << std::scientific << std::setprecision(std::numeric_limits<double>::max_digits10) << input;
119 s << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10) << input;
120 return s.str().c_str();
122 else if constexpr ( std::is_arithmetic_v<T> )
123 return std::to_string(input);
125 return typeid(T).name();
129 std::enable_if_t<std::is_enum_v<T>, std::string>
130 to_string(
const T& input)
132 return std::to_string(
static_cast<std::underlying_type_t<T>
>(input));
137 to_string(std::string s)
144 #endif // SST_CORE_FROM_STRING_H