With unrelenting power, the programmer hacks away at yet another conversion between int and string, string and double, and more. Spread throughout the code like a disease, these conversions, once deemed too simplistic for reuse, are beginning to impact the clarity of the code. The remedy is close at hand, and its called lexical_cast.
From the deep forests of Boost  come a number of useful C++ class libraries, covering an impressive range of domains numerical processing, graphs [2, 3], threads , metaprogramming, smart pointers , and much more. It is here that you find lexical_cast, a small utility for performing lexical conversions consistently and correctly.
Listing 1 demonstrates how to use lexical_cast.
Listing 1 tries to perform two conversions: one from string to double, and one from a literal string to int. The first conversion is done like this:
lexical_cast is a templated function, parameterized on the target type of the conversion. It works with all types that are streamable . If a conversion fails, lexical_cast throws an exception of type bad_lexical_cast. In Listing 1, such a failure is provoked by the second call to lexical_cast:
int i=boost::lexical_cast<int>("123 4");
The value "123 4 is clearly not convertible to an int, causing the call to fail. The protection with try/catch must only be omitted when there is absolute certainty that the conversion cannot fail.
Tedious and repetitive tasks often offer opportunities for reuse. That is definitely the case with lexical conversions, and lexical_cast adds even more value than mere reuse with its elegant resemblance of a C++ cast the syntax and semantics become obvious. Thanks to Kevlin Henney, father of lexical_cast, you dont have to do much work to benefit from this fine piece of creative engineering just visit <www.boost.org> and get on with it!
Bjorn Karlsson works as a project manager at ReadSoft. He is the kind of out-going guy who likes to read ISO/IEC 14882:98. Bjorn can be reached at [email protected].