lexical_cast_no_exceptions_test.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Unit test for boost::lexical_cast.
  2. //
  3. // See http://www.boost.org for most recent version, including documentation.
  4. //
  5. // Copyright Antony Polukhin, 2012-2019.
  6. //
  7. // Distributed under the Boost
  8. // Software License, Version 1.0. (See accompanying file
  9. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
  10. #include <boost/config.hpp>
  11. #if defined(__INTEL_COMPILER)
  12. #pragma warning(disable: 193 383 488 981 1418 1419)
  13. #elif defined(BOOST_MSVC)
  14. #pragma warning(disable: 4097 4100 4121 4127 4146 4244 4245 4511 4512 4701 4800)
  15. #endif
  16. #include <boost/lexical_cast.hpp>
  17. #include <boost/core/lightweight_test.hpp>
  18. #include <boost/range/iterator_range.hpp>
  19. #include <cstdlib>
  20. #ifndef BOOST_NO_EXCEPTIONS
  21. #error "This test must be compiled with -DBOOST_NO_EXCEPTIONS"
  22. #endif
  23. struct Escape
  24. {
  25. Escape(){}
  26. Escape(const std::string& s)
  27. : str_(s)
  28. {}
  29. std::string str_;
  30. };
  31. inline std::ostream& operator<< (std::ostream& o, const Escape& rhs)
  32. {
  33. return o << rhs.str_;
  34. }
  35. inline std::istream& operator>> (std::istream& i, Escape& rhs)
  36. {
  37. return i >> rhs.str_;
  38. }
  39. namespace boost {
  40. BOOST_NORETURN void throw_exception(std::exception const & ) {
  41. static int state = 0;
  42. ++ state;
  43. Escape v("");
  44. switch(state) {
  45. case 1:
  46. lexical_cast<char>(v); // should call boost::throw_exception
  47. std::exit(1);
  48. case 2:
  49. lexical_cast<unsigned char>(v); // should call boost::throw_exception
  50. std::exit(2);
  51. }
  52. std::exit(boost::report_errors());
  53. }
  54. }
  55. void test_exceptions_off() {
  56. using namespace boost;
  57. Escape v("");
  58. v = lexical_cast<Escape>(100);
  59. BOOST_TEST_EQ(lexical_cast<int>(v), 100);
  60. BOOST_TEST_EQ(lexical_cast<unsigned int>(v), 100u);
  61. v = lexical_cast<Escape>(0.0);
  62. BOOST_TEST_EQ(lexical_cast<double>(v), 0.0);
  63. BOOST_TEST_EQ(lexical_cast<short>(100), 100);
  64. BOOST_TEST_EQ(lexical_cast<float>(0.0), 0.0);
  65. lexical_cast<short>(700000); // should call boost::throw_exception
  66. BOOST_TEST(false);
  67. }
  68. int main() {
  69. test_exceptions_off();
  70. return boost::report_errors();
  71. }