optional_io.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. #include <istream>
  15. #include <ostream>
  16. #include "boost/none.hpp"
  17. #include "boost/optional/optional.hpp"
  18. namespace boost
  19. {
  20. template<class CharType, class CharTrait>
  21. inline
  22. std::basic_ostream<CharType, CharTrait>&
  23. operator<<(std::basic_ostream<CharType, CharTrait>& out, none_t)
  24. {
  25. if (out.good())
  26. {
  27. out << "--";
  28. }
  29. return out;
  30. }
  31. template<class CharType, class CharTrait, class T>
  32. inline
  33. std::basic_ostream<CharType, CharTrait>&
  34. operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<T> const& v)
  35. {
  36. if (out.good())
  37. {
  38. if (!v)
  39. out << "--" ;
  40. else out << ' ' << *v ;
  41. }
  42. return out;
  43. }
  44. template<class CharType, class CharTrait, class T>
  45. inline
  46. std::basic_istream<CharType, CharTrait>&
  47. operator>>(std::basic_istream<CharType, CharTrait>& in, optional<T>& v)
  48. {
  49. if (in.good())
  50. {
  51. int d = in.get();
  52. if (d == ' ')
  53. {
  54. T x;
  55. in >> x;
  56. #ifndef BOOST_OPTIONAL_DETAIL_NO_RVALUE_REFERENCES
  57. v = boost::move(x);
  58. #else
  59. v = x;
  60. #endif
  61. }
  62. else
  63. {
  64. if (d == '-')
  65. {
  66. d = in.get();
  67. if (d == '-')
  68. {
  69. v = none;
  70. return in;
  71. }
  72. }
  73. in.setstate( std::ios::failbit );
  74. }
  75. }
  76. return in;
  77. }
  78. } // namespace boost
  79. #endif