© Dmitri Nesteruk 2018
Dmitri NesterukDesign Patterns in Modern C++https://doi.org/10.1007/978-1-4842-3603-1_25

25. Maybe Monad

Dmitri Nesteruk1 
(1)
St. Petersburg, Russia
 
In C++, like in many other languages, we have different ways of expressing the presence or absence of a value. In C++ specifically, we can use any of the following:
  • Using nullptr to encode absence.

  • Using a smart pointer (e.g., shared_ptr) which, again, can be tested for presence or absence.

  • std::optional<T> is a library solution; it can either store a value of type T or std::nullopt if the value is missing.

Suppose we decide to go with the nullptr approach . In this case, let’s imagine that our domain model defines a Person who may or may not have an Address, which, in turn, can have ...

Get Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.