Representing optional values with std::optional
Although quite a minor feature in C++17, std::optional
is a neat addition to the STL library which simplifies a common case which couldn't be expressed in a clean straightforward syntax prior to std::optional
. In a nutshell, it is a small wrapper for any type where the wrapped type can be both initialized and uninitialized.
To put it in C++ lingo, std::optional
is a stack-allocated container with a max size of one.
Note
Note that the Boost Libraries has had an equivalent of std::optional,
named boost::optional
for many years.
Optional return values
Before the introduction of std::optional
, there was no clear way to define functions which may not return a defined value, such as the intersection point of two line segments. With the introduction of std::optional
, such optional return values can be clearly expressed. Following is an implementation of a function which returns an optional intersection between two lines:
// Prerequisite
class Point {......