| Home | Libraries | People | FAQ | More

### Flexibility and Adaptability to Change

> "There is nothing more constant than change" Heraclitus

Sooner or later (during initial development or in the maintenance phase) flexibility and adaptability become important. Deployment of Boost.Convert helps to adjust and to change in line with the evolution of the requirements. Say, the program flow would benefit from the non-throwing behavior. Then:

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

    // Does not throw. Returns fallback value (-1) when failed.
    int i = convert<int>("uhm", boost::cnv::lexical_cast()).value_or(-1);

    BOOST_TEST(i == -1); // Conversion failed. 'i' assigned the fallback value.

Or, the component is identified as too slow. Then the performance could be improved with minimal effort by replacing the converter:

    #include <boost/convert/strtol.hpp>
    #include <boost/convert/spirit.hpp>

    boost::cnv::lexical_cast cnv1;
    boost::cnv::strtol       cnv2;
    boost::cnv::spirit       cnv3;

    int i1 = convert<int>("123", cnv1).value();
    int i2 = convert<int>("123", cnv2).value(); // Two times faster than lexical_cast.
    int i3 = convert<int>("123", cnv3).value(); // Four times faster than lexical_cast.

If, instead, the requirements change to support more input formats or to require a certain output format, then, again, that could be accommodated with:

    #include <boost/convert/stream.hpp>

    boost::cnv::cstream cnv;

    try
    {
        int i1 = lexical_cast<int>("   123"); // Does not work.
        BOOST_TEST(!"Never reached");
    }
    catch (...) {}

    int          i2 = convert<int>("   123", cnv(std::skipws)).value(); // Success
    string       s1 = lexical_cast<string>(12.34567);
    string       s2 = convert<string>(12.34567, cnv(std::fixed)(std::setprecision(3))).value();
    string       s3 = convert<string>(12.34567, cnv(std::scientific)(std::setprecision(3))).value();
    string expected = local::is_msc ? "1.235e+001" : "1.235e+01";

    BOOST_TEST(i2 == 123);        // boost::cnv::cstream. Successfull conversion of "   123".
    BOOST_TEST(s1 == "12.34567"); // boost::lexical_cast. Precision is not configurable.
    BOOST_TEST(s2 == "12.346");   // boost::cnv::cstream. Precision was set to 3. Fixed.
    BOOST_TEST(s3 == expected);   // boost::cnv::cstream. Precision was set to 3. Scientific.