optional_io.hpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (C) 2005, Fernando Luis Cacciola Carballal.
  2. //
  3. // Use, modification, and distribution is subject to the Boost Software
  4. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/optional for documentation.
  8. //
  9. // You are welcome to contact the author at:
  10. // fernando_cacciola@hotmail.com
  11. //
  12. #ifndef BOOST_OPTIONAL_OPTIONAL_IO_FLC_19NOV2002_HPP
  13. #define BOOST_OPTIONAL_OPTIONAL_IO_FLC_19NOV2002_HPP
  14. #ifndef BOOST_NO_IOSTREAM
  15. #include <istream>
  16. #include <ostream>
  17. #include "boost/none.hpp"
  18. #include "boost/optional/optional.hpp"
  19. namespace boost
  20. {
  21. template<class CharType, class CharTrait>
  22. inline
  23. std::basic_ostream<CharType, CharTrait>&
  24. operator<<(std::basic_ostream<CharType, CharTrait>& out, none_t)
  25. {
  26. if (out.good())
  27. {
  28. out << "--";
  29. }
  30. return out;
  31. }
  32. template<class CharType, class CharTrait, class T>
  33. inline
  34. std::basic_ostream<CharType, CharTrait>&
  35. operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<T> const& v)
  36. {
  37. if (out.good())
  38. {
  39. if (!v)
  40. out << "--" ;
  41. else out << ' ' << *v ;
  42. }
  43. return out;
  44. }
  45. template<class CharType, class CharTrait, class T>
  46. inline
  47. std::basic_istream<CharType, CharTrait>&
  48. operator>>(std::basic_istream<CharType, CharTrait>& in, optional<T>& v)
  49. {
  50. if (in.good())
  51. {
  52. int d = in.get();
  53. if (d == ' ')
  54. {
  55. T x;
  56. in >> x;
  57. v = optional_detail::move(x);
  58. }
  59. else
  60. {
  61. if (d == '-')
  62. {
  63. d = in.get();
  64. if (d == '-')
  65. {
  66. v = none;
  67. return in;
  68. }
  69. }
  70. in.setstate( std::ios::failbit );
  71. }
  72. }
  73. return in;
  74. }
  75. } // namespace boost
  76. #endif // BOOST_NO_IOSTREAM
  77. #endif