| 1 | // Copyright Antony Polukhin, 2013-2024. |
| 2 | |
| 3 | // Distributed under the Boost Software License, Version 1.0. |
| 4 | // (See the accompanying file LICENSE_1_0.txt |
| 5 | // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.) |
| 6 | |
| 7 | |
| 8 | //[lexical_cast_variant_to_long_double |
| 9 | /*` |
| 10 | In this example we'll make a `to_long_double` method that converts value of the Boost.Variant to `long double`. |
| 11 | */ |
| 12 | |
| 13 | #include <boost/lexical_cast.hpp> |
| 14 | #include <boost/variant.hpp> |
| 15 | |
| 16 | struct to_long_double_functor: boost::static_visitor<long double> { |
| 17 | template <class T> |
| 18 | long double operator()(const T& v) const { |
| 19 | // Lexical cast has many optimizations including optimizations for situations that usually |
| 20 | // occur in generic programming, like std::string to std::string or arithmetic type to arithmetic type conversion. |
| 21 | return boost::lexical_cast<long double>(v); |
| 22 | } |
| 23 | }; |
| 24 | |
| 25 | // Throws `boost::bad_lexical_cast` if value of the variant is not convertible to `long double` |
| 26 | template <class Variant> |
| 27 | long double to_long_double(const Variant& v) { |
| 28 | return boost::apply_visitor(to_long_double_functor(), v); |
| 29 | } |
| 30 | |
| 31 | int main() { |
| 32 | boost::variant<char, int, std::string> v1('0'), v2("10.0001" ), v3(1); |
| 33 | |
| 34 | const long double sum = to_long_double(v: v1) + to_long_double(v: v2) + to_long_double(v: v3); |
| 35 | if (11 < sum && sum < 11.1) { |
| 36 | return 0; // OK, as expected |
| 37 | }; |
| 38 | |
| 39 | return 1; // FAIL |
| 40 | } |
| 41 | |
| 42 | //] [/lexical_cast_variant_to_long_double] |
| 43 | |