-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
C++ High Performance - Second Edition
By :
Although quite a minor feature from C++17, std::optional is a nice addition to the standard library. It simplifies a common case that couldn't be expressed in a clean and straightforward way prior to std::optional. In a nutshell, it is a small wrapper for any type where the wrapped type can be either initialized or uninitialized.
To put it in C++ lingo, std::optional is a stack-allocated container with a max size of one.
Before the introduction of std::optional, there was no clear way to define functions that 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. What follows is an implementation of a function that returns an optional intersection between two lines:
// Prerequisite
struct Point { /* ......