variant_to_long_double.cpp 1.4 KB

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