2 [section A note about optional<bool>]
4 `optional<bool>` should be used with special caution and consideration.
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
10 It should be carefully considered if an `optional<bool>` instead of a `tribool`
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:
21 optional<bool> v = try();
23 // The following intended to pass the value of 'v' to foo():
25 // But instead, the initialization state is passed
26 // due to a typo: it should have been foo(*v).
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).
33 Third, mixed comparisons with `bool` work differently than similar mixed comparisons between pointers and `bool`, so the results might surprise you:
35 optional<bool> oEmpty(none), oTrue(true), oFalse(false);
37 if (oEmpty == none); // renders true
38 if (oEmpty == false); // renders false!
39 if (oEmpty == true); // renders false!
41 if (oFalse == none); // renders false
42 if (oFalse == false); // renders true!
43 if (oFalse == true); // renders false
45 if (oTrue == none); // renders false
46 if (oTrue == false); // renders false
47 if (oTrue == true); // renders true
49 In other words, for `optional<>`, the following assertion does not hold:
51 assert((opt == false) == (!opt));