convert_from_string.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. #include <boost/lexical_cast.hpp>
  15. #endif
  16. namespace boost{ namespace math{ namespace tools{
  17. template <class T>
  18. struct convert_from_string_result
  19. {
  20. typedef typename std::conditional<std::is_constructible<T, const char*>::value, const char*, T>::type type;
  21. };
  22. template <class Real>
  23. Real convert_from_string(const char* p, const std::false_type&)
  24. {
  25. #ifdef BOOST_MATH_NO_LEXICAL_CAST
  26. // This function should not compile, we don't have the necessary functionality to support it:
  27. static_assert(sizeof(Real) == 0, "boost.lexical_cast is not supported in standalone mode.");
  28. (void)p; // Suppresses -Wunused-parameter
  29. return Real(0);
  30. #elif defined(BOOST_MATH_USE_CHARCONV_FOR_CONVERSION)
  31. if constexpr (std::is_arithmetic_v<Real>)
  32. {
  33. Real v {};
  34. std::from_chars(p, p + std::strlen(p), v);
  35. return v;
  36. }
  37. else
  38. {
  39. return boost::lexical_cast<Real>(p);
  40. }
  41. #else
  42. return boost::lexical_cast<Real>(p);
  43. #endif
  44. }
  45. template <class Real>
  46. constexpr const char* convert_from_string(const char* p, const std::true_type&) noexcept
  47. {
  48. return p;
  49. }
  50. template <class Real>
  51. constexpr typename convert_from_string_result<Real>::type convert_from_string(const char* p) noexcept((std::is_constructible<Real, const char*>::value))
  52. {
  53. return convert_from_string<Real>(p, std::is_constructible<Real, const char*>());
  54. }
  55. } // namespace tools
  56. } // namespace math
  57. } // namespace boost
  58. #endif // BOOST_MATH_TOOLS_CONVERT_FROM_STRING_INCLUDED