1 #include <string>
2 #include <type_traits>
3 namespace detail {
4 template<class T, class Enable = void>
5 struct ConvertToNumeric
6 {
7 T operator()(const std::string& str) const
8 {
9 return std::stoi(str);
10 }
11 };
12 //special cases
13 template< bool B, class T>
14 using T_enable_if_t = typename std::enable_if<B,T>::type;
15 template<class U, class T>
16 using T_same_enable_t = T_enable_if_t<std::is_same<T,U>::value, T>;
17 template<class T>
18 struct ConvertToNumeric<T, T_same_enable_t<long, T>>
19 {
20 long operator()(const std::string& str) const
21 {
22 return std::stol(str);
23 }
24 };
25 template<class T>
26 struct ConvertToNumeric<T, T_same_enable_t<unsigned long, T>>
27 {
28 unsigned long operator()(const std::string& str) const
29 {
30 return std::stoul(str);
31 }
32 };
33 template<typename T>
34 struct ConvertToNumeric<T, T_same_enable_t<long long, T>>
35 {
36 long long operator()(const std::string& str) const
37 {
38 return std::stoll(str);
39 }
40 };
41 template<typename T>
42 struct ConvertToNumeric<T, T_same_enable_t<unsigned long long, T>>
43 {
44 unsigned long long operator()(const std::string& str) const
45 {
46 return std::stoull(str);
47 }
48 };
49 template<typename T>
50 struct ConvertToNumeric<T, T_same_enable_t<float, T>>
51 {
52 float operator()(const std::string& str) const
53 {
54 return std::stof(str);
55 }
56 };
57 template<typename T>
58 struct ConvertToNumeric<T, T_same_enable_t<double, T>>
59 {
60 double operator()(const std::string& str) const
61 {
62 return std::stod(str);
63 }
64 };
65 template<typename T>
66 struct ConvertToNumeric<T, T_same_enable_t<long double, T>>
67 {
68 long double operator()(const std::string& str) const
69 {
70 return std::stold(str);
71 }
72 };
73 }
74 //this complex way, also use function template specialization
75 /*****************************************/
76 /*
77 template<typename T>
78 inline T str_to_numeric(const std::string& str)
79 {
80 return std::stoi(str);
81 }
82 template<>
83 inline long str_to_numeric<long>(const std::string& str)
84 {
85 return std::stol(str);
86 }
87 ...
88 */
89 template<typename T>
90 inline T str_to_numeric(const std::string& str)
91 {
92 using T_decay_t = typename std::decay<T>::type;
93 return detail::ConvertToNumeric<T_decay_t, T_decay_t>()(str);
94 }