Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for a snapshot of the develop branch, built from commit 0f185d9b2a.

Storage in containers

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();

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. optional<T> can also be stored as a key in std::unordered_map and std::unordered_set as it provides specializations for std::hash.