HiPipe  0.7.0
C++17 data pipeline with Python bindings.
string.hpp
1 /****************************************************************************
2  * hipipe library
3  * Copyright (c) 2017, Cognexa Solutions s.r.o.
4  * Copyright (c) 2018, Iterait a.s.
5  * Author(s) Filip Matzner
6  *
7  * This file is distributed under the MIT License.
8  * See the accompanying file LICENSE.txt for the complete license agreement.
9  ****************************************************************************/
11 
12 #pragma once
13 
14 #include <boost/lexical_cast.hpp>
15 #include <range/v3/view/transform.hpp>
16 
17 #include <algorithm>
18 #include <locale>
19 #include <experimental/filesystem>
20 #include <set>
21 #include <sstream>
22 #include <string>
23 
24 namespace hipipe::utility {
25 
32 template<typename T>
33 T string_to(const std::string& str)
34 {
35  try {
36  return boost::lexical_cast<T>(str);
37  } catch(const boost::bad_lexical_cast &) {
38  throw std::ios_base::failure{std::string{"Failed to read type <"} + typeid(T).name() +
39  "> from string \"" + str + "\"."};
40  }
41 }
42 
44 template<>
45 inline std::string string_to<std::string>(const std::string& str)
46 {
47  return str;
48 }
49 
51 template<>
52 inline std::experimental::filesystem::path
53 string_to<std::experimental::filesystem::path>(const std::string& str)
54 {
55  return str;
56 }
57 
58 namespace detail
59 {
61  const std::set<std::string> true_set =
62  {"true ", "True ", "TRUE ", "1", "y", "Y", "yes", "Yes", "YES", "on ", "On ", "ON"};
64  const std::set<std::string> false_set =
65  {"false", "False", "FALSE", "0", "n", "N", "no ", "No ", "NO ", "off", "Off", "OFF"};
66 }
67 
76 template<>
77 inline bool string_to<bool>(const std::string& str)
78 {
79  if (detail::true_set.count(str)) return true;
80  if (detail::false_set.count(str)) return false;
81  throw std::ios_base::failure{"Failed to convert string \"" + str + "\" to bool."};
82 }
83 
90 template<typename T>
91 std::string to_string(const T& value)
92 {
93  try {
94  return boost::lexical_cast<std::string>(value);
95  } catch(const boost::bad_lexical_cast &) {
96  throw std::ios_base::failure{std::string{"Failed to read string from type <"}
97  + typeid(T).name() + ">."};
98  }
99 }
100 
102 inline std::string to_string(const std::experimental::filesystem::path& path)
103 {
104  return path.string();
105 }
106 
108 inline std::string to_string(const std::string& str)
109 {
110  return str;
111 }
112 
114 inline std::string to_string(const char* const& str)
115 {
116  return str;
117 }
118 
122 inline std::string to_string(const bool& b)
123 {
124  return b ? "true" : "false";
125 }
126 
127 } // namespace hipipe
hipipe::utility::to_string
std::string to_string(const T &value)
Convert the given type to std::string.
Definition: string.hpp:90
hipipe::utility::string_to
T string_to(const std::string &str)
Convert std::string to the given type.
Definition: string.hpp:32