SST  6.0.0
StructuralSimulationToolkit
from_string.h
1 // Copyright 2009-2016 Sandia Corporation. Under the terms
2 // of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S.
3 // Government retains certain rights in this software.
4 //
5 // Copyright (c) 2009-2016, Sandia Corporation
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 
13 #ifndef SST_CORE_FROM_STRING_H
14 #define SST_CORE_FROM_STRING_H
15 
16 #include <string>
17 #include <type_traits>
18 
19 namespace SST {
20 namespace Core {
21 
22 template<class T>
23 typename std::enable_if<std::is_integral<T>::value, T >::type
24  from_string(const std::string& input)
25 {
26  if ( std::is_signed<T>::value ) {
27  if ( std::is_same<int,T>::value ) {
28  return std::stoi(input,0,0);
29  }
30  else if ( std::is_same<long,T>::value ) {
31  return std::stol(input,0,0);
32  }
33  else if ( std::is_same<long long, T>::value ) {
34  return std::stoll(input,0,0);
35  }
36  else { // Smaller than 32-bit
37  return static_cast<T>(std::stol(input,0,0));
38  }
39  }
40  else {
41  if ( std::is_same<bool, T>::value ) {
42  // valid pairs: true/false, t/f, yes/no, y/n, on/off, 1/0
43  std::string transform(input);
44  for (auto & c: transform) c = std::tolower(c);
45  if ( transform == "true" || transform == "t" || transform == "yes" || transform == "y" || transform == "on" || transform == "1" ) {
46  return true;
47  } else if ( transform == "false" || transform == "f" || transform == "no" || transform == "n" || transform == "off" || transform == "0" ) {
48  return false;
49  }
50  else {
51  throw new std::invalid_argument("from_string: no valid conversion");
52  }
53  }
54  else if ( std::is_same<unsigned long, T>::value ) {
55  return std::stoul(input,0,0);
56  }
57  else if ( std::is_same<unsigned long long, T>::value ) {
58  return std::stoull(input,0,0);
59  }
60  else { // Smaller than 32-bit
61  return static_cast<T>(std::stoul(input,0,0));
62  }
63  }
64 }
65 
66 template<class T>
67 typename std::enable_if<std::is_floating_point<T>::value, T >::type
68  from_string(const std::string& input)
69 {
70  if ( std::is_same<float, T>::value ) {
71  return stof(input);
72  }
73  else if ( std::is_same<double, T>::value ) {
74  return stod(input);
75  }
76  else if ( std::is_same<long double, T>::value ) {
77  return stold(input);
78  }
79 }
80 
81 template<class T>
82 typename std::enable_if<std::is_class<T>::value, T >::type
83  from_string(const std::string& input) {
84  static_assert(std::is_constructible<T,std::string>::value,"ERROR: from_string can only be used with integral and floating point types and with classes that have a constructor that takes a single string as input.\n");
85  return T(input);
86 }
87 
88 } // end namespace Core
89 } // end namespace SST
90 
91 #endif // SST_CORE_FROM_STRING_H
Definition: action.cc:17