...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Objects of type optional<T>
are intended to be used in places where
objects of type T
would
but which might be uninitialized. Hence, optional<T>
's purpose is to formalize the additional
possibly uninitialized state. From the perspective of this role, optional<T>
can have the same operational semantics of T
plus the additional semantics corresponding to this special state. As such,
optional<T>
could be thought of as a supertype of T
. Of course, we can't do that in C++,
so we need to compose the desired semantics using a different mechanism.
Doing it the other way around, that is, making optional<T>
a subtype of
T
is not only conceptually
wrong but also impractical: it is not allowed to derive from a non-class
type, such as a built-in type.
We can draw from the purpose of optional<T>
the required basic semantics:
T
's swap).
Additional operations are useful, such as converting constructors and converting assignments, in-place construction and assignment, and safe value access via a pointer to the wrapped object or null.