• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1
2[section IO operators]
3
4It 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.
5
6``
7#include <iostream>
8#include <boost/optional/optional_io.hpp>
9
10int main()
11{
12  boost::optional<int> o1 = 1, oN = boost::none;
13  std::cout << o1;
14  std::cin >> oN;
15}
16``
17
18The 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:
19
20``
21#include <cassert>
22#include <sstream>
23#include <boost/optional/optional_io.hpp>
24
25int main()
26{
27  boost::optional<int> o1 = 1, oN = boost::none;
28  boost::optional<int> x1, x2;
29  std::stringstream s;
30  s << o1 << oN;
31  s >> x1 >> x2;
32  assert (o1 == x1);
33  assert (oN == x2);
34}
35``
36
37[endsect]
38