### Include Headers for Boost Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started Includes necessary headers for using Boost Convert, particularly for the lexical_cast functionality. ```cpp #include #include ``` -------------------------------- ### Basic Type Conversions with Boost Convert and Lexical Cast Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started Demonstrates basic integer and string conversions using both boost::lexical_cast and boost::convert, with and without an explicit converter. Includes error handling via try-catch blocks. ```cpp try { auto cnv = boost::cnv::lexical_cast(); // boost::lexical_cast-based converter int i1 = lexical_cast("123"); // boost::lexical_cast standard deployment int i2 = convert("123").value(); // boost::convert with the default converter int i3 = convert("123", cnv).value(); // boost::convert with an explicit converter string s1 = lexical_cast(123); // boost::lexical_cast standard deployment string s2 = convert(123).value(); // boost::convert with the default converter string s3 = convert(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; } ``` -------------------------------- ### Using Namespace Declarations for Boost Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started Declares namespaces for standard C++ string and Boost Convert elements to simplify their usage in code. ```cpp using std::string; using boost::lexical_cast; using boost::convert; ``` -------------------------------- ### Define Default Converter for Boost Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started Defines a default converter policy for Boost Convert using the lexical_cast functionality. This is optional but can simplify conversion calls. ```cpp // Definition of the default converter (optional) struct boost::cnv::by_default : boost::cnv::lexical_cast {}; ``` -------------------------------- ### Boost charconv Converter Basic Deployment (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/charconv_converter Includes necessary headers and sets up the default charconv converter for use with Boost.Convert. This example demonstrates the basic setup for the converter. ```cpp #include #include using std::string; using boost::convert; namespace cnv = boost::cnv; namespace arg = boost::cnv::parameter; struct cnv::by_default : boost::cnv::charconv {}; ``` -------------------------------- ### Boost Convert Function Template Usage Examples - C++ Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/convert_8hpp_1abfe68a78b7e9e775f590f528e93d7d69 Examples demonstrating the usage of boost::convert with the default converter (boost::cnv::by_default). It shows how to convert string representations to integers and floating-point numbers to strings, returning a boost::optional. ```cpp struct boost::cnv::by_default : boost::cnv::cstream {}; // boost::cnv::cstream (through boost::cnv::by_default) is deployed // as the default converter when no converter is provided explicitly. boost::optional i = boost::convert("12"); boost::optional s = boost::convert(123.456); ``` -------------------------------- ### Boost.Convert Stream Converter Setup Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/stream_converter Includes necessary headers and defines a default stream converter for basic usage. It sets up the boost::cnv::by_default to use boost::cnv::cstream. ```cpp #include #include #include using std::string; using boost::convert; struct boost::cnv::by_default : boost::cnv::cstream {}; ``` -------------------------------- ### Boost.Convert Lexical Cast Setup and Usage Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail This snippet demonstrates setting up and using the boost::cnv::lexical_cast converter. It includes necessary headers, namespace imports, and the definition of the default converter. The examples showcase direct replacement of boost::lexical_cast and error handling using value() and value_or() for different data types. ```cpp #include #include #include using std::string; using boost::convert; using boost::lexical_cast; struct boost::cnv::by_default : boost::cnv::lexical_cast {}; ``` ```cpp int i1 = lexical_cast("123"); // Throws if the conversion fails. int i2 = convert("123").value(); // Throws if the conversion fails. int i3 = convert("uhm").value_or(-1); // Returns -1 if the conversion fails. string s1 = lexical_cast(123); string s2 = convert(123).value(); BOOST_TEST(i1 == 123); BOOST_TEST(i2 == 123); BOOST_TEST(i3 == -1); BOOST_TEST(s1 == "123"); BOOST_TEST(s2 == "123"); ``` -------------------------------- ### Boost.Convert: Stream Conversion with Formatting (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started/flexibility_and_adaptability_to_change Illustrates using Boost.Convert with iostream manipulators for flexible input and output formatting. This example shows successful conversion of a string with leading whitespace to an integer and controlled formatting of floating-point numbers to strings using fixed and scientific notations. ```cpp #include #include #include #include #include #include try { int i1 = boost::lexical_cast(" 123"); // Does not work. BOOST_TEST(false, "Never reached"); } catch (...) {} auto cnv = boost::cnv::cstream(); int i2 = boost::convert(" 123", cnv(std::skipws)).value(); // Success std::string s1 = boost::lexical_cast(12.34567); std::string s2 = boost::convert(12.34567, cnv(std::fixed)(std::setprecision(3))).value(); std::string s3 = boost::convert(12.34567, cnv(std::scientific)(std::setprecision(3))).value(); std::string expected = (boost::detail::winapi::is_msc_compiler() ? "1.235e+001" : "1.235e+01"); BOOST_TEST(i2 == 123); // boost::cnv::cstream. Successful 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. ``` -------------------------------- ### Boost.Convert Function Template Example (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/convert_8hpp_1af4b24fd41e07b42f1900230c275da40c Demonstrates the usage of the `boost::convert` function template for type conversions using `boost::cnv::cstream`. It shows converting a string to an integer and a double to a string, with results wrapped in `boost::optional`. ```cpp #include #include #include #include int main() { boost::cnv::cstream cnv; boost::optional i = boost::convert("12", cnv); boost::optional s = boost::convert(123.456, cnv); if (i) { std::cout << "Converted integer: " << *i << std::endl; } else { std::cout << "Failed to convert to integer." << std::endl; } if (s) { std::cout << "Converted string: " << *s << std::endl; } else { std::cout << "Failed to convert to string." << std::endl; } return 0; } ``` -------------------------------- ### Boost.Convert apply Example: String to Integer Conversion Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/convert_8hpp_1a69930a236250df33cca405b0fe20b795 An example demonstrating the usage of `boost::cnv::apply` to convert an array of C-style strings to a vector of integers. It utilizes `std::transform` and `boost::cnv::cstream` for flexible conversion, with a default value of -1 for failed conversions. ```cpp std::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; boost::cnv::cstream cnv; cnv(std::hex)(std::skipws); std::transform( strs.begin(), strs.end(), std::back_inserter(ints), boost::cnv::apply(std::cref(cnv)).value_or(-1)); ``` -------------------------------- ### Example of Compiler Optimization (Elision) for Boost.Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This snippet illustrates how the essential Boost.Convert API is typically optimized out by the compiler when used in a direct assignment to boost::optional, highlighting its efficiency. ```C++ boost::optional out = boost::convert(in); ``` -------------------------------- ### MBCS to Unicode String Converter Example C++ Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters Demonstrates a custom converter for operating-system-specific MBCS (Multi-Byte Character Set) string format conversion to UCS-2 or UCS-4 format based on wchar_t size. This is an example of a purpose-built converter for a specific string encoding transformation. ```cpp void operator()(std::string const&, boost::optional&) const; ``` -------------------------------- ### String to Int Conversion with std::transform and boost::lexical_cast (Exception) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/algorithms Demonstrates a basic string to integer conversion using std::transform and boost::lexical_cast. This example shows a scenario where an invalid input string will cause an exception, halting the conversion process. It highlights a limitation that led to the development of Boost.Convert. ```cpp std::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; try { std::transform(strs.begin(), strs.end(), std::back_inserter(ints), std::bind(boost::lexical_cast, std::placeholders::_1)); BOOST_TEST(0 && "Never reached!"); } catch (std::exception&) { BOOST_TEST(ints.size() == 0); // No strings converted. } ``` -------------------------------- ### Boost Convert Locale Support Demonstration (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/stream_converter/locale_support This C++ code snippet demonstrates using Boost.Convert's `cstream` with different locales (Russian and English) to format a double-precision number into a string. It sets precision, uppercase, and scientific notation parameters and verifies the output against expected locale-specific strings. Dependencies include Boost.Convert and standard C++ locale facilities. ```cpp namespace cnv = boost::cnv; namespace arg = boost::cnv::parameter; boost::cnv::cstream cnv; std::locale rus_locale; std::locale eng_locale; char const* eng_locale_name = test::cnv::is_msc ? "English_United States.1251" : "en_US.UTF-8"; char const* rus_locale_name = test::cnv::is_msc ? "Russian_Russia.1251" : "ru_RU.UTF-8"; char const* rus_expected = test::cnv::is_msc ? "1,235e-002" : "1,235e-02"; char const* eng_expected = test::cnv::is_msc ? "1.235e-002" : "1.235e-02"; char const* dbl_expected = test::cnv::is_msc ? "1.2345E-002" : "1.2345E-02"; // cnv(std::setprecision(4))(std::uppercase)(std::scientific); cnv(arg::precision = 4) (arg::uppercase = true) (arg::notation = cnv::notation::scientific); double double_v01 = convert(dbl_expected, cnv).value_or(0); string double_s02 = convert(double_v01, cnv).value_or("bad"); BOOST_TEST(dbl_expected == double_s02); try { rus_locale = std::locale(rus_locale_name); } catch (...) { printf("Bad locale %s.\n", rus_locale_name); exit(1); } try { eng_locale = std::locale(eng_locale_name); } catch (...) { printf("Bad locale %s.\n", eng_locale_name); exit(1); } // cnv(std::setprecision(3))(std::nouppercase); cnv(arg::precision = 3)(arg::uppercase = false); string double_rus = convert(double_v01, cnv(rus_locale)).value_or("bad double_rus"); string double_eng = convert(double_v01, cnv(eng_locale)).value_or("bad double_eng"); BOOST_TEST(double_rus == rus_expected); BOOST_TEST(double_eng == eng_expected); ``` -------------------------------- ### Boost Convert: Numeric Base Formatting (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/strtol_converter/formatting_support Demonstrates formatting integer values into strings with specified numeric bases (binary, octal, decimal, hexadecimal) using the Boost.Convert library. It includes examples for both `std::string` and `std::wstring` output types, utilizing `boost::cnv::strtol` for conversion. ```c++ #include #include using std::string; using std::wstring; using boost::convert; namespace cnv = boost::cnv; namespace arg = boost::cnv::parameter; ``` ```c++ boost::cnv::strtol cnv; BOOST_TEST( "11111110" == convert< string>(254, cnv(arg::base = cnv::base::bin)).value()); BOOST_TEST( "254" == convert< string>(254, cnv(arg::base = cnv::base::dec)).value()); BOOST_TEST( "FE" == convert< string>(254, cnv(arg::base = cnv::base::hex)).value()); BOOST_TEST( "376" == convert< string>(254, cnv(arg::base = cnv::base::oct)).value()); ``` ```c++ BOOST_TEST(L"11111110" == convert(254, cnv(arg::base = cnv::base::bin)).value()); BOOST_TEST( L"254" == convert(254, cnv(arg::base = cnv::base::dec)).value()); BOOST_TEST( L"FE" == convert(254, cnv(arg::base = cnv::base::hex)).value()); BOOST_TEST( L"376" == convert(254, cnv(arg::base = cnv::base::oct)).value()); ``` -------------------------------- ### Int to String Conversion with boost::cnv::cstream and Formatting Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/algorithms Demonstrates integer to string conversion using boost::cnv::cstream with std::transform and various formatting flags (std::hex, std::uppercase, std::showbase). This example shows how to apply complex formatting to the output strings and highlights the use of std::cref to handle non-copyable converter objects within standard algorithms. ```cpp std::array ints = {{ 15, 16, 17 }}; std::vector strs; boost::cnv::cstream cnv; cnv(std::hex)(std::uppercase)(std::showbase); std::transform(ints.begin(), ints.end(), std::back_inserter(strs), boost::cnv::apply(std::cref(cnv))); BOOST_TEST(strs.size() == 3); BOOST_TEST(strs[0] == "0XF"); // 15 BOOST_TEST(strs[1] == "0X10"); // 16 BOOST_TEST(strs[2] == "0X11"); // 17 ``` -------------------------------- ### Convert with optional and logging failed conversions Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/error_detection An example demonstrating how to use boost::optional to handle conversion results. If the conversion fails (optional is empty), a log message is generated before providing a fallback value. ```cpp boost::optional res = boost::convert(str, cnv); if (!res) log("str conversion failed!"); int i1 = res.value_or(fallback_value); // ...proceed ``` -------------------------------- ### Example: Conversion Functions for 'change' Type (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/integration_of_user_types Provides an implementation of conversion functions for the 'change' type, enabling its use with converters like `boost::cnv::strtol`. These functions convert between 'change' objects and strings via `boost::optional`. ```cpp inline void operator>>(change chg, boost::optional& str) { str = chg == change::up ? "up" : chg == change::dn ? "dn" : "no"; } inline void operator>>(std::string const& str, boost::optional& chg) { /**/ if (str == "up") chg = change::up; else if (str == "dn") chg = change::dn; else if (str == "no") chg = change::no; } ``` -------------------------------- ### Implement strtol-based Converter with boost::optional in C++ Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/converter_signature Example implementation of signature #2 converter using strtol() to convert C-string to integer. Demonstrates lazy initialization approach where boost::optional storage is allocated without initialization, and the converter only initializes the output value upon successful conversion. Validates result range and ensures complete string consumption. ```cpp void operator()(char const* str_in, boost::optional& result_out) const { char const* str_end = str_in + strlen(str_in); char* cnv_end = 0; long int result = ::strtol(str_in, &cnv_end, base_); if (INT_MIN <= result && result <= INT_MAX && cnv_end == str_end) result_out = int(result); } ``` -------------------------------- ### String to Int Conversion with boost::cnv::cstream (Non-Throwing) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/algorithms Illustrates string to integer conversion using boost::cnv::cstream with std::transform and the non-throwing 'value_or' option. This example shows how to handle invalid input strings gracefully by assigning a default value (-1) and ensuring the conversion process completes for all elements, including formatted inputs. ```cpp std::transform(strs.begin(), strs.end(), std::back_inserter(ints), boost::cnv::apply(std::cref(cnv(std::hex)(std::skipws)))).value_or(-1)); BOOST_TEST(ints.size() == 3); BOOST_TEST(ints[0] == 5); BOOST_TEST(ints[1] == 15); BOOST_TEST(ints[2] == -1); // Failed conversion ``` -------------------------------- ### String to Int Conversion with boost::cnv::cstream (Exception) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/algorithms Demonstrates string to integer conversion using boost::cnv::cstream with std::transform, supporting formatting like hexadecimal input and skipping whitespace. This example shows the exception-throwing behavior when an invalid string is encountered, converting only valid inputs before an exception occurs. ```cpp std::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; boost::cnv::cstream cnv; try { std::transform(strs.begin(), strs.end(), std::back_inserter(ints), boost::cnv::apply(std::cref(cnv(std::hex)(std::skipws)))); BOOST_TEST(0 && "Never reached!"); } catch (boost::bad_optional_access const&) { BOOST_TEST(ints.size() == 2); // Only the first two strings converted. BOOST_TEST(ints[0] == 5); // " 5" BOOST_TEST(ints[1] == 15); // "0XF" // "not an int" causes the exception thrown. } ``` -------------------------------- ### Boost Convert: Forced TypeIn Conversion Example Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/algorithms This snippet demonstrates how to explicitly specify the source type (TypeIn) using boost::cnv::apply. It converts an array of 'change::value_type' to readable strings ('no', 'up', 'dn') by forcing the TypeIn to be 'change', overcoming the default deduction that resulted in numerical strings. ```cpp #include #include #include #include #include #include #include // Assume 'change' and 'change::value_type' are defined elsewhere // For example: struct change { enum value_type { no, up, dn }; }; int main() { std::array chgs2 = {{ change::no, change::up, change::dn }}; auto strs3 = std::vector(); auto cnv = boost::cnv::cstream(); std::transform(chgs2.begin(), chgs2.end(), std::back_inserter(strs3), boost::cnv::apply(std::cref(cnv))); // Forced TypeIn is 'change' BOOST_TEST(strs3.size() == 3); BOOST_TEST(strs3[0] == "no"); BOOST_TEST(strs3[1] == "up"); BOOST_TEST(strs3[2] == "dn"); return 0; } ``` -------------------------------- ### Boost Convert: Deduced TypeIn Conversion Example Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/algorithms This snippet demonstrates the default behavior of boost::cnv::apply where the source type (TypeIn) is deduced. It shows how an array of a custom 'change' type converts to strings like 'no', 'up', 'dn', while an array of its underlying 'change::value_type' converts to numerical strings '0', '1', '2' due to type deduction. ```cpp #include #include #include #include #include #include #include // Assume 'change' and 'change::value_type' are defined elsewhere // For example: struct change { enum value_type { no, up, dn }; }; int main() { std::array chgs1 = {{ change::no, change::up, change::dn }}; std::array chgs2 = {{ change::no, change::up, change::dn }}; auto strs1 = std::vector(); auto strs2 = std::vector(); auto cnv = boost::cnv::cstream(); std::transform(chgs1.begin(), chgs1.end(), std::back_inserter(strs1), boost::cnv::apply(std::cref(cnv))); // Deduced TypeIn is 'change' std::transform(chgs2.begin(), chgs2.end(), std::back_inserter(strs2), boost::cnv::apply(std::cref(cnv))); // Deduced TypeIn is 'change::value_type' BOOST_TEST(strs1.size() == 3); BOOST_TEST(strs1[0] == "no"); BOOST_TEST(strs1[1] == "up"); BOOST_TEST(strs1[2] == "dn"); BOOST_TEST(strs2.size() == 3); BOOST_TEST(strs2[0] == "0"); BOOST_TEST(strs2[1] == "1"); BOOST_TEST(strs2[2] == "2"); return 0; } ``` -------------------------------- ### Hexadecimal String to Integer Conversion with Boost.Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/introduction Demonstrates converting an array of hexadecimal string representations of integers to actual integers using Boost.Convert. It configures the converter to read hexadecimal values and skip whitespace, and uses std::transform with boost::cnv::apply to process the conversion. Failed conversions are assigned a fallback value of -1. This example utilizes std::array, std::vector, boost::cnv::cstream, and std::transform. ```cpp std::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; boost::cnv::cstream cnv; // Configure converter to read hexadecimal, skip (leading) white spaces. cnv(std::hex)(std::skipws); std::transform(strs.begin(), strs.end(), std::back_inserter(ints), boost::cnv::apply(std::cref(cnv)).value_or(-1)); BOOST_TEST(ints.size() == 3); // Number of values processed. BOOST_TEST(ints[0] == 5); // " 5" BOOST_TEST(ints[1] == 15); // "0XF" BOOST_TEST(ints[2] == -1); // "not an int" ``` -------------------------------- ### Achieving Initial Behaviors with the Simplified Boost.Convert Signature Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This snippet demonstrates how the behaviors of the initial #1 and #2 Boost.Convert signatures can be achieved using the simplified #3 signature that returns a boost::optional. ```C++ Out out1 = boost::convert(in).value(); // #3 with #1 behavior Out out2 = boost::convert(in).value_or(fallback); // #3 with #2 behavior ``` -------------------------------- ### Simplified User Interface Signatures using boost::optional Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This snippet presents further simplification of the Boost.Convert interface by leveraging the capabilities of boost::optional. It shows how to achieve the behavior of previous signatures with more concise and idiomatic C++. ```C++ void convert (boost::optional&, In const&); //#3 ``` ```C++ boost::optional convert (In const&); //#3 ``` -------------------------------- ### Boost.Convert: Performance Comparison of Converters (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started/flexibility_and_adaptability_to_change Compares the performance of different Boost.Convert converters: lexical_cast, strtol, and spirit. It shows how to instantiate and use these converters to achieve faster data conversions, especially when dealing with performance-critical sections of code. ```cpp #include #include #include auto cnv1 = boost::cnv::lexical_cast(); auto cnv2 = boost::cnv::strtol(); auto cnv3 = boost::cnv::spirit(); int i1 = boost::convert("123", cnv1).value(); int i2 = boost::convert("123", cnv2).value(); // Two times faster than lexical_cast. int i3 = boost::convert("123", cnv3).value(); // Four times faster than lexical_cast. ``` -------------------------------- ### Get Character Static Function (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/structboost_1_1cnv_1_1strtol A private static utility function `get_char` that takes an `int` value and returns an `int`. This function likely assists in character-level processing during string conversions. ```C++ static int get_char(int v); ``` -------------------------------- ### Boost Convert Function Template Synopsis - C++ Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/convert_8hpp_1abfe68a78b7e9e775f590f528e93d7d69 The synopsis for the boost::convert function template, found in . It outlines the template parameters and return type for performing type conversions. ```cpp // In header: template boost::optional< TypeOut > convert(TypeIn const & value_in); ``` -------------------------------- ### Basic Boost.Convert Stream Conversions Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/stream_converter Demonstrates fundamental conversion operations using boost::convert. It shows converting strings to integers and integers to strings, including error handling with value_or. ```cpp int i2 = convert("123").value(); // Throws when fails. int i3 = convert("uhm").value_or(-1); // Returns -1 when fails. string s2 = convert(123).value(); BOOST_TEST(i2 == 123); BOOST_TEST(i3 == -1); BOOST_TEST(s2 == "123"); ``` -------------------------------- ### Consolidated and Idiomatic Boost.Convert User Interface Signatures Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This snippet shows a consolidated set of Boost.Convert signatures that are functionally complete and avoid clashes. It highlights how #1 and #2 are now redundant due to the expressive power of the #3 signature with boost::optional. ```C++ Out convert (In const&); //#1 Out convert (In const&, Out const&); //#2 boost::optional convert (In const&); //#3 bool convert (boost::optional&, In const&, Out const&); //#4 ``` -------------------------------- ### Convert with exception handling using lexical_cast and convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/error_detection Shows how both boost::lexical_cast and boost::convert can throw exceptions on conversion failure. This example uses a try-catch block to handle potential conversion errors. ```cpp try { int i1 = lexical_cast(str); // Throws if the conversion fails. int i2 = convert(str, cnv).value(); // Throws if the conversion fails. } catch (...) { process_failure(); } ``` -------------------------------- ### Example: Stream Operators for 'change' Type (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/integration_of_user_types Provides a concrete implementation of input and output stream operators for a custom 'change' enum-like type. This demonstrates how to make a user-defined type compatible with std::iostream for Boost.Convert. ```cpp struct change { enum value_type { no, up, dn }; change(value_type v =no) : value_(v) {} bool operator==(change v) const { return value_ == v.value_; } value_type value() const { return value_; } private: value_type value_; }; std::istream& operator>>(std::istream& stream, change& chg) { std::string str; stream >> str; /**/ if (str == "up") chg = change::up; else if (str == "dn") chg = change::dn; else if (str == "no") chg = change::no; else stream.setstate(std::ios_base::failbit); return stream; } std::ostream& operator<<(std::ostream& stream, change const& chg) { return stream << (chg == change::up ? "up" : chg == change::dn ? "dn" : "no"); } ``` -------------------------------- ### Specializing make_default for custom types Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/make__default_8hpp_1aa346257c4ecfade8a05b9fc245c59bca Provides an example of how to specialize the boost::make_default template for a custom type. This allows boost::make_default to create instances of types that do not have a default constructor by defining how to construct them with specific parameters. ```cpp namespace boost { template<> inline Type make_default() { return Type(parameters); } } ``` -------------------------------- ### Boost Convert: Handling Conversion Failures with Fallback Mechanisms Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/alternative_interface Demonstrates the usage of the alternative `boost::convert` interface to handle conversion failures. It shows how to provide a fallback value, a fallback function, and how to catch exceptions when `boost::throw_on_failure` is used. ```cpp struct fallback_func { int operator()() const { log("Failed to convert"); return 42; } }; // Error-processing behavior are specified unambiguously and uniformly. // a) i1: Returns the provided fallback value; // b) i2: Calls the provided failure-processing function; // c) i3: Throws an exception. int i1 = convert(str, cnv, fallback_value); int i2 = convert(str, cnv, fallback_func()); try { // Throwing behavior specified explicitly rather than implied. int i3 = convert(str, cnv, boost::throw_on_failure); } catch (boost::bad_optional_access const&) { // Handle failed conversion. } ``` -------------------------------- ### Boost.Convert C++ Header and Function Declarations Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert_c___reference This snippet shows the core declarations from the header. It includes the `boost` namespace, `throw_on_failure` setting, and overloaded `convert` functions for optional and non-optional conversions. It also details the `cnv` namespace with `reference` and `apply` utilities for configuring converters. ```cpp namespace boost { _unspecified_ throw_on_failure; template boost::optional< TypeOut > convert(TypeIn const &, Converter const &); template boost::optional< TypeOut > convert(TypeIn const &); // Boost.Convert non-optional deployment interface. template TypeOut convert(TypeIn const & value_in, Converter const & converter, _unspecified_); template std::enable_if< is_convertible< Fallback, TypeOut >::value, TypeOut >::type convert(TypeIn const & value_in, Converter const & converter, Fallback const & fallback); template std::enable_if< cnv::is_fun< Fallback, TypeOut >::value, TypeOut >::type convert(TypeIn const & value_in, Converter const & converter, Fallback fallback); namespace cnv { template struct reference; template struct reference; typedef char const * char_cptr; template reference< Converter, TypeOut, TypeIn > apply(Converter const &); template reference< Converter, TypeOut, void > apply(Converter const & cnv); } } ``` -------------------------------- ### Performance Benchmarking of Integer to String Conversions (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/performance/the_bigger_picture Compares the performance of converting an integer to std::string and a custom my_string using different conversion strategies (strtol, spirit, cstream, charconv). The code demonstrates how to measure and print these conversion times. ```cpp printf("strtol int-to std::string/small-string: %.2f/%.2f seconds.\n", local::to_str(boost::cnv::strtol()), local::to_str< my_string, int>(boost::cnv::strtol())); printf("spirit int-to std::string/small-string: %.2f/%.2f seconds.\n", local::to_str(boost::cnv::spirit()), local::to_str< my_string, int>(boost::cnv::spirit())); printf("stream int-to std::string/small-string: %.2f/%.2f seconds.\n", local::to_str(boost::cnv::cstream()), local::to_str< my_string, int>(boost::cnv::cstream())); printf("charconv int-to std::string/small-string: %.2f/%.2f seconds.\n", local::to_str(boost::cnv::charconv()), local::to_str< my_string, int>(boost::cnv::charconv())); ``` -------------------------------- ### Get Character Format Configuration - C++ charconv::chars_format Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/structboost_1_1cnv_1_1charconv Member function that returns the current std::chars_format configuration used by the charconv converter. This allows querying which formatting style (fixed, scientific, hex, etc.) is applied during conversions. ```cpp std::chars_format chars_format() const; ``` -------------------------------- ### User Interface Signatures with boost::optional for Boost.Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This snippet illustrates the refinement of Boost.Convert's user interface by incorporating boost::optional. This change aims to reduce overhead associated with traditional output parameters and improve the handling of potential conversion failures. ```C++ bool convert (boost::optional&, In const&); //#3 bool convert (boost::optional&, In const&, Out const&); //#4 ``` -------------------------------- ### Boost.Convert Stream Generic Formatting Parameters Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/stream_converter Shows an alternative, generic interface for specifying formatting options like numeric base, case, and notation using boost::cnv::parameter. ```cpp namespace cnv = boost::cnv; namespace arg = boost::cnv::parameter; ccnv(arg::base = cnv::base::dec) (arg::uppercase = true) (arg::notation = cnv::notation::scientific); ``` -------------------------------- ### Boost.Convert Stream Numeric Base Conversions Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/stream_converter Demonstrates converting between different numeric bases (decimal, octal, hexadecimal) using stream manipulators and generic parameters with boost::convert. ```cpp using std::string; using std::wstring; using boost::convert; boost::cnv::cstream ccnv; BOOST_TEST(convert( "11", ccnv(std::hex)).value_or(0) == 17); // 11(16) = 17(10) BOOST_TEST(convert( "11", ccnv(std::oct)).value_or(0) == 9); // 11(8) = 9(10) BOOST_TEST(convert( "11", ccnv(std::dec)).value_or(0) == 11); BOOST_TEST(convert( 18, ccnv(std::hex)).value_or("bad") == "12"); // 18(10) = 12(16) BOOST_TEST(convert( 10, ccnv(std::oct)).value_or("bad") == "12"); // 10(10) = 12(8) BOOST_TEST(convert( 12, ccnv(std::dec)).value_or("bad") == "12"); BOOST_TEST(convert(255, ccnv(arg::base = boost::cnv::base::oct)).value_or("bad") == "377"); BOOST_TEST(convert(255, ccnv(arg::base = boost::cnv::base::hex)).value_or("bad") == "ff"); BOOST_TEST(convert(255, ccnv(arg::base = boost::cnv::base::dec)).value_or("bad") == "255"); ccnv(std::showbase); BOOST_TEST(convert(18, ccnv(std::hex)).value_or("bad") == "0x12"); BOOST_TEST(convert(10, ccnv(std::oct)).value_or("bad") == "012"); ccnv(std::uppercase); BOOST_TEST(convert(18, ccnv(std::hex)).value_or("bad") == "0X12"); ``` ```cpp namespace cnv = boost::cnv; namespace arg = boost::cnv::parameter; BOOST_TEST(convert("11", ccnv(arg::base = cnv::base::hex)).value_or(0) == 17); BOOST_TEST(convert("11", ccnv(arg::base = cnv::base::oct)).value_or(0) == 9); BOOST_TEST(convert("11", ccnv(arg::base = cnv::base::dec)).value_or(0) == 11); ``` -------------------------------- ### Boost Convert: Main Interface for Fallback Handling Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/alternative_interface Illustrates how the main `boost::convert` interface can achieve similar fallback behaviors using methods like `value_or` and `value_or_eval`. This provides a more concise way to manage conversion outcomes. ```cpp // Still, the described interfaces are convenience wrappers around the main interface which provides the described behavior with: int m1 = convert(str, cnv).value_or(fallback_value); int m2 = convert(str, cnv).value_or_eval(fallback_func()); int m3 = convert(str, cnv).value(); ``` -------------------------------- ### User-Defined API using Boost.Optional Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This C++ snippet demonstrates how users can build their own conversion APIs leveraging Boost.Optional. It shows a simple convert function that uses an underlying convert function and provides a fallback value. ```cpp template Out convert(In const& in, Out const& fallback) //#2 { return convert(in).value_or(fallback); } ``` -------------------------------- ### Explicit Conversion with Boost.Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/default_converter Demonstrates how to perform an explicit type conversion using the `boost::convert` function by providing a converter instance. This method offers high flexibility and configurability. ```cpp int i = boost::convert("123", converter).value(); ``` -------------------------------- ### Plain Function Converter C++ Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters Demonstrates using a traditional function as a converter with the boost::convert API. The function signature matches the converter requirements with input and optional output parameters, allowing simple function-based conversion. ```cpp void plain_old_func(string const& value_in, boost::optional& value_out) int v01 = convert(str, plain_old_func).value_or(-1); ``` -------------------------------- ### Custom String Type Conversion with boost::cnv::stream Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/stream_converter/supported_string_types/custom_string_types Demonstrates converting between custom string types and numeric types using boost::cnv::cstream converter with precision and fixed-point formatting. The example shows converting a custom string to integer, and floating-point values to custom strings with specified precision. Custom string types must be contiguous sequences and support begin()/end() for input, or provide a constructor accepting (char const* beg, char const* end) for output. ```cpp boost::cnv::cstream cnv; my_string my_str("123"); cnv(std::setprecision(2))(std::fixed); BOOST_TEST(convert(my_str, cnv).value_or(0) == 123); BOOST_TEST(convert( 99.999, cnv).value_or("bad") == "100.00"); BOOST_TEST(convert( 99.949, cnv).value_or("bad") == "99.95"); BOOST_TEST(convert(-99.949, cnv).value_or("bad") == "-99.95"); ``` -------------------------------- ### Initial Conventional User Interface Signatures for Boost.Convert Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This snippet shows the first attempt at defining the user interface for Boost.Convert using conventional C++ function overloading. It includes four variations to handle different error reporting and result output mechanisms. ```C++ template Out convert (In const&); //#1 template Out convert (In const&, Out const& fallback); //#2 template bool convert (Out& result_out, In const&); //#3 template bool convert (Out& result_out, In const&, Out const& fallback); //#4 ``` -------------------------------- ### Boost.Convert Conventional Interface with Fallbacks Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/design_notes/user_interface_signature This C++ snippet illustrates the alternative, conventional interface provided by Boost.Convert. It showcases three variations for handling conversion failures, using a fallback value, a fallback functor, or throwing an exception. ```cpp Out convert(In const&, Converter const&, Out const& fallback_value); Out convert(In const&, Converter const&, Functor const& fallback_functor); Out convert(In const&, Converter const&, boost::throw_on_failure); ``` -------------------------------- ### Boost.Convert: Non-throwing Conversion with Fallback Value (C++) Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/getting_started/flexibility_and_adaptability_to_change Demonstrates how to use Boost.Convert for non-throwing integer conversions from a string. If the conversion fails, it returns a specified fallback value. This is useful for handling potentially invalid input without program termination. ```cpp #include #include #include // Does not throw. Returns fallback value (-1) when failed. int i = boost::convert("uhm", boost::cnv::lexical_cast()).value_or(-1); // BOOST_TEST(i == -1); // Conversion failed. 'i' assigned the fallback value. ``` -------------------------------- ### Format Numeric Base (bin, oct, dec, hex) with Boost C++ Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/boost_convert/converters_detail/charconv_converter/formatting_support Demonstrates converting an integer to its string representation in binary, decimal, hexadecimal, and octal formats using Boost's charconv utility. Requires the Boost C++ Libraries. Input is an integer, output is a string. ```cpp boost::cnv::charconv cnv; BOOST_TEST( "11111110" == convert< string>(254, cnv(arg::base = cnv::base::bin)).value()); BOOST_TEST( "254" == convert< string>(254, cnv(arg::base = cnv::base::dec)).value()); BOOST_TEST( "fe" == convert< string>(254, cnv(arg::base = cnv::base::hex)).value()); BOOST_TEST( "376" == convert< string>(254, cnv(arg::base = cnv::base::oct)).value()); ``` -------------------------------- ### Boost.Convert printf struct synopsis Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/structboost_1_1cnv_1_1printf The synopsis for the boost::cnv::printf struct, found in ``. It includes type definitions and declarations for public and private member functions used for string conversion. ```cpp // In header: struct printf : public boost::cnv::cnvbase< boost::cnv::printf > { // types typedef boost::cnv::printf this_type; typedef boost::cnv::cnvbase< this_type > base_type; // public member functions template cnv::range< char * > to_str(in_type, char *) const; template void str_to(cnv::range< string_type >, optional< out_type > &) const; // private member functions template int pos() const; char_cptr printf_format(int) const; char_cptr sscanf_format(int) const; }; ``` -------------------------------- ### Boost.Convert apply Function Template Synopsis Source: https://www.boost.org/doc/libs/latest/libs/convert/doc/html/doxygen/boost_convert_c___reference/convert_8hpp_1a69930a236250df33cca405b0fe20b795 This snippet shows the C++ synopsis for the `boost::cnv::apply` function template. It is defined in the `` header and is used with the Boost.Convert library for type conversions. ```cpp // In header: template reference< Converter, TypeOut, TypeIn > apply(Converter const & cnv); ```