...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Suppose you want to ask users to choose some number (an int
).
One of the valid responses is to choose nothing, which is represented by
an uninitialized optional<int>
.
You want to make a histogram showing how many times each choice was made.
You can use an std::map
:
std::map<boost::optional<int>, int> choices; for (int i = 0; i < LIMIT; ++i) { boost::optional<int> choice = readChoice(); ++choices[choice]; }
This works because optional<T>
is LessThanComparable
whenever T
is LessThanComparable
. In this case
the state of being uninitialized is treated as a yet another value of T
, which is compared less than any value
of T
.