3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
14 #include "support/convert.h"
15 #include "support/docstring.h"
17 #include <boost/lexical_cast.hpp>
21 //needed for Mac OSX 10.5.2 Leopard
28 // A version of lexical cast that does not throw. Useful for when we convert to string
29 template<typename To, typename From>
30 To lexical_cast(From const & value, To const & defaultResult = To())
33 return boost::lexical_cast<To>(value);
35 // Ignore all exceptions and use default.
46 string convert<string>(bool b)
48 return (b ? "true" : "false");
53 string convert<string>(char c)
60 string convert<string>(short unsigned int sui)
62 return lexical_cast<string>(sui);
67 string convert<string>(int i)
69 return lexical_cast<string>(i);
74 docstring convert<docstring>(int i)
76 return from_ascii(lexical_cast<string>(i));
81 string convert<string>(unsigned int ui)
83 return lexical_cast<string>(ui);
88 docstring convert<docstring>(unsigned int ui)
90 return from_ascii(lexical_cast<string>(ui));
95 string convert<string>(unsigned long ul)
97 return lexical_cast<string>(ul);
102 docstring convert<docstring>(unsigned long ul)
104 return from_ascii(lexical_cast<string>(ul));
108 #ifdef HAVE_LONG_LONG_INT
110 string convert<string>(unsigned long long ull)
112 return lexical_cast<string>(ull);
117 docstring convert<docstring>(unsigned long long ull)
119 return from_ascii(lexical_cast<string>(ull));
125 string convert<string>(long l)
127 return lexical_cast<string>(l);
132 docstring convert<docstring>(long l)
134 return from_ascii(lexical_cast<string>(l));
138 #ifdef HAVE_LONG_LONG_INT
140 string convert<string>(long long ll)
142 return lexical_cast<string>(ll);
147 docstring convert<docstring>(long long ll)
149 return from_ascii(lexical_cast<string>(ll));
155 string convert<string>(float f)
157 std::ostringstream val;
164 string convert<string>(double d)
166 std::ostringstream val;
173 docstring convert<docstring>(double d)
175 return from_ascii(convert<string>(d));
180 int convert<int>(string const s)
182 return int(strtol(s.c_str(), nullptr, 10));
186 int convert(std::string const & s, int base)
188 return int(strtol(s.c_str(), nullptr, base));
193 int convert<int>(docstring const s)
195 return int(strtol(to_ascii(s).c_str(), nullptr, 10));
200 unsigned int convert<unsigned int>(string const s)
202 return static_cast<unsigned int>(strtoul(s.c_str(), nullptr, 10));
207 unsigned long convert<unsigned long>(string const s)
209 return strtoul(s.c_str(), nullptr, 10);
214 double convert<double>(string const s)
216 return strtod(s.c_str(), nullptr);
221 int convert<int>(char const * cptr)
223 return int(strtol(cptr, nullptr, 10));
228 double convert<double>(char const * cptr)
230 return strtod(cptr, nullptr);