Chapter 6. Boost.LexicalCast
Example 6.1. Using boost::lexical_cast
uses streams internally to perform the conversion. Therefore, only types with overloaded operator<<
and operator>>
can be converted. However, boost::lexical_cast
can be optimized for certain types to implement a more efficient conversion.
#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>
{
{
int i = boost::lexical_cast<int>("abc");
}
catch (const boost::bad_lexical_cast &e)
{
std::cerr << e.what() << '\n';
}
If a conversion fails, an exception of type boost::bad_lexical_cast
, which is derived from , is thrown. Example 6.2 throws an exception because the string “abc” cannot be converted to a number of type int
.