25 #ifndef GOBY_UTIL_AS_H
26 #define GOBY_UTIL_AS_H
35 #include <boost/algorithm/string.hpp>
36 #include <boost/lexical_cast.hpp>
37 #include <boost/mpl/and.hpp>
38 #include <boost/mpl/logical.hpp>
39 #include <boost/numeric/conversion/cast.hpp>
40 #include <boost/type_traits.hpp>
41 #include <boost/utility.hpp>
50 template <
typename To>
51 typename boost::enable_if<boost::is_arithmetic<To>, To>
::type
56 return boost::lexical_cast<To>(from);
58 catch (boost::bad_lexical_cast&)
61 return std::numeric_limits<To>::has_quiet_NaN ? std::numeric_limits<To>::quiet_NaN()
62 : std::numeric_limits<To>::max();
67 template <
typename To>
72 return static_cast<To
>(boost::lexical_cast<int>(from));
74 catch (boost::bad_lexical_cast&)
76 return static_cast<To
>(0);
80 template <
typename To>
85 return boost::lexical_cast<To>(from);
87 catch (boost::bad_lexical_cast&)
95 return (boost::iequals(from,
"true") || boost::iequals(from,
"1"));
98 template <>
inline std::string _as_from_string<std::string>(
const std::string& from)
103 template <
typename To,
typename From> std::string
_as_to_string(
const From& from)
107 return boost::lexical_cast<std::string>(from);
109 catch (boost::bad_lexical_cast&)
111 return std::string();
116 template <>
inline std::string _as_to_string<std::string, bool>(
const bool& from)
118 return from ?
"true" :
"false";
121 template <>
inline std::string _as_to_string<std::string, std::string>(
const std::string& from)
126 template <
typename To,
typename From>
131 return boost::numeric_cast<To>(from);
133 catch (boost::bad_numeric_cast&)
136 return std::numeric_limits<To>::has_quiet_NaN ? std::numeric_limits<To>::quiet_NaN()
137 : std::numeric_limits<To>::max();
141 template <
typename To,
typename From>
147 template <
typename To> To
as(
const std::string& from) {
return _as_from_string<To>(from); }
149 template <
typename To,
typename From>
150 typename boost::enable_if<boost::is_same<To, std::string>, To>
::type as(
const From& from)
152 return _as_to_string<To, From>(from);
155 template <
typename To,
typename From>
156 typename boost::enable_if<boost::mpl::and_<boost::is_arithmetic<To>, boost::is_arithmetic<From> >,
160 return _as_numeric<To, From>(from);
164 template <
typename To,
typename From>
165 typename boost::enable_if<boost::mpl::and_<boost::is_enum<To>, boost::is_arithmetic<From> >,
169 return static_cast<To
>(from);
179 template <
typename To,
typename From>
186 inline std::string as<std::string, double>(
const double& from,
int precision,
189 std::stringstream out;
198 out << std::setprecision(precision) << from;
205 std::stringstream out;
214 out << std::setprecision(precision) << from;