Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Getting Started

Basic Deployment
Flexibility and Adaptability to Change
Basic Conversion-Failure Detection
[Note] Note

Given the ubiquity of boost::lexical_cast and the familiarity of the programming community with it, here and further in the documentation boost::lexical_cast is often mentioned as a reference.

For die-hard boost::lexical_cast users or as a transitional path to boost::convert, one of boost::convert deployments is not that different from boost::lexical_cast. In fact, the original boost::lexical_cast functionality is easily deployed through boost::convert interface:

#include <boost/convert.hpp>
#include <boost/convert/lexical_cast.hpp>

using std::string;
using boost::lexical_cast;
using boost::convert;

// Definition of the default converter (optional)
struct boost::cnv::by_default : boost::cnv::lexical_cast {};

try
{
    auto  cnv = boost::cnv::lexical_cast();        // boost::lexical_cast-based converter
    int    i1 = lexical_cast<int>("123");          // boost::lexical_cast standard deployment
    int    i2 = convert<int>("123").value();       // boost::convert with the default converter
    int    i3 = convert<int>("123", cnv).value();  // boost::convert with an explicit converter
    string s1 = lexical_cast<string>(123);         // boost::lexical_cast standard deployment
    string s2 = convert<string>(123).value();      // boost::convert with the default converter
    string s3 = convert<string>(123, cnv).value(); // boost::convert with an explicit converter

    BOOST_TEST(i1 == 123);
    BOOST_TEST(i2 == 123);
    BOOST_TEST(i3 == 123);
    BOOST_TEST(s1 == "123");
    BOOST_TEST(s2 == "123");
    BOOST_TEST(s3 == "123");
}
catch (std::exception const& ex)
{
    // Please be aware that the conversion requests above can fail.
    // Use try'n'catch blocks to handle any exceptions thrown.
    // Ignore this at your peril!
    std::cerr << "Exception " << ex.what() << std::endl;
}

[Important] Important

As we explore boost::convert behavior and interface further, at first they might appear unduly complex, verbose, etc... nothing like atoi()... so famous for all the wrong reasons. :-) It is important to remember that a conversion request is only a request which may succeed but may also fail... which might not be as rare or as exceptional as one might hope. boost::convert (as well as boost::lexical_cast) behavior and interfaces reflect that reality.


PrevUpHomeNext