13_relational_operators.qbk 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 
  2. [section Relational operators]
  3. Type `optional<T>` is __SGI_EQUALITY_COMPARABLE__ whenever `T` is __SGI_EQUALITY_COMPARABLE__. Two optional objects containing a value compare in the same way as their contained values. The uninitialized state of `optional<T>` is treated as a distinct value, equal to itself, and unequal to any value of type `T`:
  4. boost::optional<int> oN = boost::none;
  5. boost::optional<int> o0 = 0;
  6. boost::optional<int> o1 = 1;
  7. assert(oN != o0);
  8. assert(o1 != oN);
  9. assert(o0 != o1);
  10. assert(oN == oN);
  11. assert(o0 == o0);
  12. The converting constructor from `T` as well as from `boost::none` implies the existence and semantics of the mixed comparison between `T` and `optional<T>` as well as between `none_t` and `optionl<T>`:
  13. assert(oN != 0);
  14. assert(o1 != boost::none);
  15. assert(o0 != 1);
  16. assert(oN == boost::none);
  17. assert(o0 == 0);
  18. This mixed comparison has a practical interpretation, which is occasionally useful:
  19. boost::optional<int> choice = ask_user();
  20. if (choice == 2)
  21. start_procedure_2();
  22. In the above example, the meaning of the comparison is 'user chose number 2'. If user chose nothing, he didn't choose number 2.
  23. In case where `optional<T>` is compared to `none`, it is not required that `T` be __SGI_EQUALITY_COMPARABLE__.
  24. In a similar manner, type `optional<T>` is __SGI_LESS_THAN_COMPARABLE__ whenever `T` is __SGI_LESS_THAN_COMPARABLE__. The optional object containing no value is compared less than any value of `T`. To illustrate this, if the default ordering of `size_t` is {`0`, `1`, `2`, ...}, the default ordering of `optional<size_t>` is {`boost::none`, `0`, `1`, `2`, ...}. This order does not have a practical interpretation. The goal is to have any semantically correct default ordering in order for `optional<T>` to be usable in ordered associative containers (wherever `T` is usable).
  25. Mixed relational operators are the only case where the contained value of an optional object can be inspected without the usage of value accessing function (`operator*`, `value`, `value_or`).
  26. [endsect]