convert_from_string.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright John Maddock 2016.
  2. // Copyright Matt Borland 2023.
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_MATH_TOOLS_CONVERT_FROM_STRING_INCLUDED
  7. #define BOOST_MATH_TOOLS_CONVERT_FROM_STRING_INCLUDED
  8. #ifdef _MSC_VER
  9. #pragma once
  10. #endif
  11. #include <boost/math/tools/config.hpp>
  12. #include <type_traits>
  13. #ifndef BOOST_MATH_STANDALONE
  14. #if defined(_MSC_VER) || defined(__GNUC__)
  15. # pragma push_macro( "I" )
  16. # undef I
  17. #endif
  18. #include <boost/lexical_cast.hpp>
  19. #if defined(_MSC_VER) || defined(__GNUC__)
  20. # pragma pop_macro( "I" )
  21. #endif
  22. #endif
  23. namespace boost{ namespace math{ namespace tools{
  24. template <class T>
  25. struct convert_from_string_result
  26. {
  27. typedef typename std::conditional<std::is_constructible<T, const char*>::value, const char*, T>::type type;
  28. };
  29. template <class Real>
  30. Real convert_from_string(const char* p, const std::false_type&)
  31. {
  32. #ifdef BOOST_MATH_NO_LEXICAL_CAST
  33. // This function should not compile, we don't have the necessary functionality to support it:
  34. static_assert(sizeof(Real) == 0, "boost.lexical_cast is not supported in standalone mode.");
  35. (void)p; // Suppresses -Wunused-parameter
  36. return Real(0);
  37. #elif defined(BOOST_MATH_USE_CHARCONV_FOR_CONVERSION)
  38. if constexpr (std::is_arithmetic_v<Real>)
  39. {
  40. Real v {};
  41. std::from_chars(p, p + std::strlen(p), v);
  42. return v;
  43. }
  44. else
  45. {
  46. return boost::lexical_cast<Real>(p);
  47. }
  48. #else
  49. return boost::lexical_cast<Real>(p);
  50. #endif
  51. }
  52. template <class Real>
  53. constexpr const char* convert_from_string(const char* p, const std::true_type&) noexcept
  54. {
  55. return p;
  56. }
  57. template <class Real>
  58. constexpr typename convert_from_string_result<Real>::type convert_from_string(const char* p) noexcept((std::is_constructible<Real, const char*>::value))
  59. {
  60. return convert_from_string<Real>(p, std::is_constructible<Real, const char*>());
  61. }
  62. } // namespace tools
  63. } // namespace math
  64. } // namespace boost
  65. #endif // BOOST_MATH_TOOLS_CONVERT_FROM_STRING_INCLUDED