SST 12.1.0
Structural Simulation Toolkit
from_string.h
1// Copyright 2009-2022 NTESS. Under the terms
2// of Contract DE-NA0003525 with NTESS, the U.S.
3// Government retains certain rights in this software.
4//
5// Copyright (c) 2009-2022, NTESS
6// All rights reserved.
7//
8// This file is part of the SST software package. For license
9// information, see the LICENSE file in the top level directory of the
10// distribution.
11
12#ifndef SST_CORE_FROM_STRING_H
13#define SST_CORE_FROM_STRING_H
14
15#include <stdexcept>
16#include <string>
17#include <type_traits>
18
19namespace SST {
20namespace Core {
21
22template <class T>
23typename std::enable_if<std::is_integral<T>::value, T>::type
24from_string(const std::string& input)
25{
26 if ( std::is_signed<T>::value ) {
27 if ( std::is_same<int, T>::value ) { return std::stoi(input, nullptr, 0); }
28 else if ( std::is_same<long, T>::value ) {
29 return std::stol(input, nullptr, 0);
30 }
31 else if ( std::is_same<long long, T>::value ) {
32 return std::stoll(input, nullptr, 0);
33 }
34 else { // Smaller than 32-bit
35 return static_cast<T>(std::stol(input, nullptr, 0));
36 }
37 }
38 else {
39 if ( std::is_same<bool, T>::value ) {
40 // valid pairs: true/false, t/f, yes/no, y/n, on/off, 1/0
41 std::string transform(input);
42 for ( auto& c : transform )
43 c = std::tolower(c);
44 if ( transform == "true" || transform == "t" || transform == "yes" || transform == "y" ||
45 transform == "on" || transform == "1" ) {
46 return true;
47 }
48 else if (
49 transform == "false" || transform == "f" || transform == "no" || transform == "n" ||
50 transform == "off" || transform == "0" ) {
51 return false;
52 }
53 else {
54 throw new std::invalid_argument("from_string: no valid conversion");
55 }
56 }
57 else if ( std::is_same<unsigned long, T>::value ) {
58 return std::stoul(input, nullptr, 0);
59 }
60 else if ( std::is_same<unsigned long long, T>::value ) {
61 return std::stoull(input, nullptr, 0);
62 }
63 else { // Smaller than 32-bit
64 return static_cast<T>(std::stoul(input, nullptr, 0));
65 }
66 }
67}
68
69template <class T>
70typename std::enable_if<std::is_floating_point<T>::value, T>::type
71from_string(const std::string& input)
72{
73 if ( std::is_same<float, T>::value ) { return stof(input); }
74 else if ( std::is_same<double, T>::value ) {
75 return stod(input);
76 }
77 else if ( std::is_same<long double, T>::value ) {
78 return stold(input);
79 }
80 else { // make compiler happy
81 return stod(input);
82 }
83}
84
85template <class T>
86typename std::enable_if<std::is_class<T>::value, T>::type
87from_string(const std::string& input)
88{
89 static_assert(
90 std::is_constructible<T, std::string>::value,
91 "ERROR: from_string can only be used with integral and floating point types and with classes that have a "
92 "constructor that takes a single string as input.\n");
93 return T(input);
94}
95
96} // end namespace Core
97} // end namespace SST
98
99#endif // SST_CORE_FROM_STRING_H