Imported Upstream version 1.57.0
[platform/upstream/boost.git] / libs / optional / doc / 16_optional_bool.qbk
1 
2 [section A note about optional<bool>]
3
4 `optional<bool>` should be used with special caution and consideration.
5
6 First, it is functionally similar to a tristate boolean (false, maybe, true)
7 —such as __BOOST_TRIBOOL__— except that in a tristate boolean, the maybe state
8 [_represents a valid value], unlike the corresponding state of an uninitialized
9 `optional<bool>`.
10 It should be carefully considered if an `optional<bool>` instead of a `tribool`
11 is really needed.
12
13 Second, although `optional<>` provides a contextual conversion to `bool` in C++11,
14  this falls back to an implicit conversion on older compilers. This conversion refers
15  to the initialization state and not to the contained value. Using `optional<bool>`
16  can lead to subtle errors due to the implicit `bool` conversion:
17
18     void foo ( bool v ) ;
19     void bar()
20     {
21         optional<bool> v = try();
22
23         // The following intended to pass the value of 'v' to foo():
24         foo(v);
25         // But instead, the initialization state is passed
26         // due to a typo: it should have been foo(*v).
27     }
28
29 The only implicit conversion is to `bool`, and it is safe in the sense that
30 typical integral promotions don't apply (i.e. if `foo()` takes an `int`
31 instead, it won't compile).
32
33 Third, mixed comparisons with `bool` work differently than similar mixed comparisons between pointers and `bool`, so the results might surprise you:
34
35     optional<bool> oEmpty(none), oTrue(true), oFalse(false);
36     
37     if (oEmpty == none);  // renders true
38     if (oEmpty == false); // renders false!
39     if (oEmpty == true);  // renders false!
40      
41     if (oFalse == none);  // renders false
42     if (oFalse == false); // renders true!
43     if (oFalse == true);  // renders false
44     
45     if (oTrue == none);   // renders false
46     if (oTrue == false);  // renders false
47     if (oTrue == true);   // renders true
48
49 In other words, for `optional<>`, the following assertion does not hold:
50
51     assert((opt == false) == (!opt));
52 [endsect]