File: 12_relational_operators.qbk

package info (click to toggle)
boost1.88 1.88.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 576,932 kB
  • sloc: cpp: 4,149,234; xml: 136,789; ansic: 35,092; python: 33,910; asm: 5,698; sh: 4,604; ada: 1,681; makefile: 1,633; pascal: 1,139; perl: 1,124; sql: 640; yacc: 478; ruby: 271; java: 77; lisp: 24; csh: 6
file content (37 lines) | stat: -rw-r--r-- 2,105 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

[section Relational operators]

Type `optional<T>` is __STD_EQUALITY_COMPARABLE__ whenever `T` is __STD_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`:

    boost::optional<int> oN = boost::none;
    boost::optional<int> o0 = 0;
    boost::optional<int> o1 = 1;

    assert(oN != o0);
    assert(o1 != oN);
    assert(o0 != o1);
    assert(oN == oN);
    assert(o0 == o0);

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 `optional<T>`:

    assert(oN != 0);
    assert(o1 != boost::none);
    assert(o0 != 1);
    assert(oN == boost::none);
    assert(o0 == 0);

This mixed comparison has a practical interpretation, which is occasionally useful:

    boost::optional<int> choice = ask_user();
    if (choice == 2)
        start_procedure_2();

In the above example, the meaning of the comparison is 'user chose number 2'. If user chose nothing, he didn't choose number 2.

In case where `optional<T>` is compared to `none`, it is not required that `T` be __STD_EQUALITY_COMPARABLE__.

In a similar manner, type `optional<T>` is __STD_LESS_THAN_COMPARABLE__ whenever `T` is __STD_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).

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`).
[endsect]