1 <!-- saved from url=(0022)http://internet.e-mail -->
2 <!doctype html public
"-//W3C//DTD HTML Transitional 4.0//EN">
5 <title>lexical_cast
</title>
6 <meta name=
"author" content=
"Kevlin Henney, mailto:kevlin@curbralan.com">
7 <meta name=
"generator" content=
"Microsoft FrontPage 5.0">
9 <body bgcolor=
"#FFFFFF" text=
"#000000">
10 <h1><img src=
"../../boost.png" alt=
"boost.png (6897 bytes)" align=
"center" width=
"277" height=
"86">Header
11 <a href=
"../../boost/lexical_cast.hpp">boost/lexical_cast.hpp
</a></h1>
14 <a href=
"#motivation">Motivation
</a></li>
16 <a href=
"#examples">Examples
</a></li>
18 <a href=
"#synopsis">Synopsis
</a></li>
20 <a href=
"#lexical_cast"><code>lexical_cast
</code></a></li>
22 <a href=
"#bad_lexical_cast"><code>bad_lexical_cast
</code></a></li>
24 <a href=
"#faq">Frequently Asked Questions
</a></li>
26 <a href=
"#references">References
</a></li>
28 <a href=
"#changes">Changes
</a></li>
31 <h2><a name=
"motivation">Motivation
</a></h2>
32 Sometimes a value must be converted to a literal text form, such as an
<code>int
</code>
33 represented as a
<code>string
</code>, or vice-versa, when a
<code>string
</code>
34 is interpreted as an
<code>int
</code>. Such examples are common when converting
35 between data types internal to a program and representation external to a
36 program, such as windows and configuration files.
38 The standard C and C++ libraries offer a number of facilities for performing
39 such conversions. However, they vary with their ease of use, extensibility, and
42 For instance, there are a number of limitations with the family of standard C
43 functions typified by
<code>atoi
</code>:
46 Conversion is supported in one direction only: from text to internal data type.
47 Converting the other way using the C library requires either the inconvenience
48 and compromised safety of the
<code>sprintf
</code> function, or the loss of
49 portability associated with non-standard functions such as
<code>itoa
</code>.
52 The range of types supported is only a subset of the built-in numeric types,
53 namely
<code>int
</code>,
<code>long
</code>, and
<code>double
</code>.
56 The range of types cannot be extended in a uniform manner. For instance,
57 conversion from string representation to
<code>complex
</code> or
<code>rational
</code>.
60 The standard C functions typified by
<code>strtol
</code> have the same basic
61 limitations, but offer finer control over the conversion process. However, for
62 the common case such control is often either not required or not used. The
<code>scanf
</code>
63 family of functions offer even greater control, but also lack safety and ease
66 The standard C++ library offers
<code>stringstream
</code> for the kind of
67 in-core formatting being discussed. It offers a great deal of control over the
68 formatting and conversion of I/O to and from arbitrary types through text.
69 However, for simple conversions direct use of
<code>stringstream
</code> can be
70 either clumsy (with the introduction of extra local variables and the loss of
71 infix-expression convenience) or obscure (where
<code>stringstream
</code>
72 objects are created as temporary objects in an expression). Facets provide a
73 comprehensive concept and facility for controlling textual representation, but
74 their perceived complexity and high entry level requires an extreme degree of
75 involvement for simple conversions, and excludes all but a few programmers.
77 The
<code>lexical_cast
</code> function template offers a convenient and
78 consistent form for supporting common conversions to and from arbitrary types
79 when they are represented as text. The simplification it offers is in
80 expression-level convenience for such conversions. For more involved
81 conversions, such as where precision or formatting need tighter control than is
82 offered by the default behavior of
<code>lexical_cast
</code>, the conventional
<code>
83 stringstream
</code> approach is recommended. Where the conversions are
84 numeric to numeric,
<code><a href=
"../numeric/conversion/doc/html/boost_numericconversion/improved_numeric_cast__.html">numeric_cast
</a></code>
85 may offer more reasonable behavior than
<code>lexical_cast
</code>.
87 For a good discussion of the options and issues involved in string-based
88 formatting, including comparison of
<code>stringstream
</code>,
<code>lexical_cast
</code>,
89 and others, see Herb Sutter's article,
<a href=
"http://www.gotw.ca/publications/mill19.htm">
90 <i>The String Formatters of Manor Farm
</i></a>.
93 <h2><a name=
"examples">Examples
</a></h2>
94 The following example treats command line arguments as a sequence of numeric
96 <pre>int main(int argc, char * argv[])
98 using boost::lexical_cast;
99 using boost::bad_lexical_cast;
101 std::vector
<short
> args;
107 args.push_back(lexical_cast
<short
>(*argv));
109 catch(bad_lexical_cast
&)
117 </blockquote>The following example uses numeric data in a string expression:
<blockquote>
118 <pre>void log_message(const std::string
&);
120 void log_errno(int yoko)
122 log_message(
"Error
" + boost::lexical_cast
<std::string
>(yoko) +
":
" + strerror(yoko));
127 <h2><a name=
"synopsis">Synopsis
</a></h2>
128 Library features defined in
<a href=
"../../boost/lexical_cast.hpp"><code>"boost/lexical_cast.hpp
"</code></a>:
132 class
<a href=
"#bad_lexical_cast">bad_lexical_cast
</a>;
133 template
<typename Target, typename Source
>
134 Target
<a href=
"#lexical_cast">lexical_cast
</a>(const Source
& arg);
137 </blockquote>Unit test defined in
<a href=
"lexical_cast_test.cpp"><code>"lexical_cast_test.cpp
"</code></a>.
140 <h2><a name=
"lexical_cast"><code>lexical_cast
</code></a></h2>
142 <pre>template
<typename Target, typename Source
>
143 Target lexical_cast(const Source
& arg);
145 </blockquote>Returns the result of streaming
<code>arg
</code> into a
146 standard library string-based stream and then out as a
<code>Target
</code> object.
147 Where
<code>Target
</code> is either
<code>std::string
</code>
148 or
<code>std::wstring
</code>, stream extraction takes the whole content
149 of the string, including spaces, rather than relying on the default
150 <code>operator
>></code> behavior.
151 If the conversion is unsuccessful, a
<a href=
"#bad_lexical_cast">
152 <code>bad_lexical_cast
</code></a> exception is thrown.
154 The requirements on the argument and result types are:
157 <code>Source
</code> is
<i>OutputStreamable
</i>, meaning that an
<code>operator
<<</code>
158 is defined that takes a
<code>std::ostream
</code> or
<code>std::wostream
</code> object on the
159 left hand side and an instance of the argument type on the right.
162 <code>Target
</code> is
<i>InputStreamable
</i>, meaning that an
<code>operator
>></code>
163 is defined that takes a
<code>std::istream
</code> or
<code>std::wistream
</code> object on the left hand side
164 and an instance of the result type on the right.
167 <code>Target
</code> is
<i>CopyConstructible
</i> [
20.1.3].
170 <code>Target
</code> is
<i>DefaultConstructible
</i>, meaning that it is possible
171 to
<i>default-initialize
</i> an object of that type [
8.5,
20.1.4].
174 The character type of the underlying stream is assumed to be
<code>char
</code> unless
175 either the
<code>Source
</code> or the
<code>Target
</code> requires wide-character
176 streaming, in which case the underlying stream uses
<code>wchar_t
</code>.
177 <code>Source
</code> types that require wide-character streaming are
<code>wchar_t
</code>,
178 <code>wchar_t *
</code>, and
<code>std::wstring
</code>.
<code>Target
</code> types that
179 require wide-character streaming are
<code>wchar_t
</code> and
<code>std::wstring
</code>.
181 Where a higher degree of control is required over conversions,
<code>std::stringstream
</code>
182 and
<code>std::wstringstream
</code> offer a more appropriate path. Where non-stream-based conversions are
183 required,
<code>lexical_cast
</code>
184 is the wrong tool for the job and is not special-cased for such scenarios.
187 <h2><a name=
"bad_lexical_cast"><code>bad_lexical_cast
</code></a></h2>
189 <pre>class bad_lexical_cast : public std::bad_cast
192 ... //
<i>same member function interface as
</i> std::exception
195 </blockquote>Exception used to indicate runtime
<a href=
"#lexical_cast"><code>lexical_cast
</code></a>
199 <h2><a name=
"BOOST_LEXICAL_CAST_ASSUME_C_LOCALE"><code>BOOST_LEXICAL_CAST_ASSUME_C_LOCALE
</code></a></h2>
200 <blockquote><pre>#define BOOST_LEXICAL_CAST_ASSUME_C_LOCALE
204 g++ -DBOOST_LEXICAL_CAST_ASSUME_C_LOCALE ... (gcc on Linux/Unix)
205 cl.exe /DBOOST_LEXICAL_CAST_ASSUME_C_LOCALE ... (Visual C++ on Windows)
207 Eliminate an overhead of
<code>std::locale
</code> if your program runs in the
"C" locale. If the option is set but a program runs in other locale,
<code>lexical_cast
</code> result is unspecified.
210 <h2><a name=
"faq">Frequently Asked Questions
</h2>
211 <p> Q: Why does
<code>lexical_cast
<int8_t
>(
"127")
</code> throw
<code>bad_lexical_cast
</code>?
212 <br> A: The type
<code>int8_t
</code> is a typedef to
<code>char
</code> or
<code>signed char
</code>.
213 Lexical conversion to these types is simply reading a byte from source but since the source has
214 more than one byte, the exception is thrown.
215 <p>Please use other integer types such as
<code>int
</code> or
<code>short int
</code>. If bounds checking
216 is important, you can also call
<a href=
"../../libs/numeric/conversion/doc/html/boost_numericconversion/improved_numeric_cast__.html">numeric_cast
</a>:
218 <pre><a href=
"../../libs/numeric/conversion/doc/html/boost_numericconversion/improved_numeric_cast__.html">numeric_cast
</a><int8_t
>(lexical_cast
<int
>(
"127"));
</pre>
220 <p> Q: What does
<code>lexical_cast
<std::string
></code> of an
<code>int8_t
</code> or
<code>uint8_t
</code> not do what I expect?
221 <br> A: As above, note that
<code>int8_t
</code> and
<code>uint8_t
</code> are actually chars and are formatted as such. To avoid this, cast to an integer type first:
223 <pre>lexical_cast
<std::string
>(static_cast
<int
>(n));
</pre>
225 <p> Q: The implementation always resets the
<code>ios_base::skipws
</code> flag of an underlying stream object. It breaks my
<code>operator
>></code> that works only in presence of this flag. Can you remove code that resets the flag?
226 <br> A: May be in a future version. There is no requirement in
<a href=
"#n1973">[N1973]
</a> to reset the flag but remember that
<a href=
"#n1973">[N1973]
</a> is not yet accepted by the committee. By the way, it's a great opportunity to make your
<code>operator
>></code> conform to the standard. Read a good C++ book, study
<code>std::sentry
</code> and
<a href=
"../../libs/io/doc/ios_state.html">ios_state_saver
</a>.
228 <h2><a name=
"references">References
</h2>
230 <a name=
"n1973"></a><li> [N1973] Kevlin Henney, Beman Dawes, Lexical Conversion Library Proposal for TR2,
231 <a href=
"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1973.html">N1973
</a>.
232 <a name=
"tuning"></a><li> [Tuning] Alexander Nasonov, Fine Tuning for lexical_cast,
233 <a href=
"http://accu.org/index.php/journals/1375">Overload #
74</a> (
<a href=
"http://www.accu.org/var/uploads/journals/overload74.pdf">PDF
</a>),
236 <h2><a name=
"changes">Changes
</a></h2>
237 <h3>August, October
2006:
</h3>
239 <li>Better performance for many combinations of
<code>Source
</code> and
<code>Target
</code>
240 types. Refer to
<a href=
"#tuning">[Tuning]
</a> for more details.
245 <li>Call-by-const reference for the parameters. This requires partial specialization
246 of class templates, so it doesn't work for MSVC
6, and it uses the original
247 pass by value there.
<br>
249 <li>The MSVC
6 support is deprecated, and will be removed in a future Boost
255 <li>The previous version of
<code>lexical_cast
</code> used the default stream
256 precision for reading and writing floating-point numbers. For numerics that
257 have a corresponding specialization of
<code>std::numeric_limits
</code>, the
258 current version now chooses a precision to match.
<br>
259 <li>The previous version of
<code>lexical_cast
</code> did not support conversion
260 to or from any wide-character-based types. For compilers with full language
261 and library support for wide characters,
<code>lexical_cast
</code> now supports
262 conversions from
<code>wchar_t
</code>,
<code>wchar_t *
</code>, and
<code>std::wstring
</code>
263 and to
<code>wchar_t
</code> and
<code>std::wstring
</code>.
<br>
264 <li>The previous version of
<code>lexical_cast
</code> assumed that the conventional
265 stream extractor operators were sufficient for reading values. However, string
266 I/O is asymmetric, with the result that spaces play the role of I/O separators
267 rather than string content. The current version fixes this error for
<code>std::string
</code>
268 and, where supported,
<code>std::wstring
</code>:
<code>lexical_cast
<std::string
>(
"Hello,
269 World")
</code> succeeds instead of failing with a
<code>bad_lexical_cast
</code>
271 <li>The previous version of
<code>lexical_cast
</code> allowed unsafe and meaningless
272 conversions to pointers. The current version now throws a
<code>bad_lexical_cast
</code>
273 for conversions to pointers:
<code>lexical_cast
<char *
>(
"Goodbye, World")
</code>
274 now throws an exception instead of causing undefined behavior.
279 <div align=
"right"><small><i>© Copyright Kevlin Henney,
2000–2005</i></small></div>