14_io.qbk 886 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 
  2. [section IO operators]
  3. It is possible to use `optional<T>` with IO streams, provided that `T` can be used with streams. IOStream operators are defined in a separate header.
  4. ``
  5. #include <iostream>
  6. #include <boost/optional/optional_io.hpp>
  7. int main()
  8. {
  9. boost::optional<int> o1 = 1, oN = boost::none;
  10. std::cout << o1;
  11. std::cin >> oN;
  12. }
  13. ``
  14. The current implementation does not guarantee any particular output. What it guarantees is that if streaming out and then back in `T` gives the same value, then streaming out and then back in `optional<T>` will also give back the same result:
  15. ``
  16. #include <cassert>
  17. #include <sstream>
  18. #include <boost/optional/optional_io.hpp>
  19. int main()
  20. {
  21. boost::optional<int> o1 = 1, oN = boost::none;
  22. boost::optional<int> x1, x2;
  23. std::stringstream s;
  24. s << o1 << oN;
  25. s >> x1 >> x2;
  26. assert (o1 == x1);
  27. assert (oN == x2);
  28. }
  29. ``
  30. [endsect]