optional_io.hpp 2.0 KB

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