-
Book Overview & Buying
-
Table Of Contents
C++ STL Cookbook - Second Edition
By :
Introduced with C++17, the std::optional class holds an optional value.
There are any number of scenarios where this can be useful, including long-running processes where a result may not yet be available, API callbacks where a function may or may not return a value, lazy initialization where an object is constructed only when needed, or any use case where a value may or may not be valid.
Consider the case where you have a function that may or may not return a value. For example, a function that checks if a number is prime, but returns the first factor if there is one. This function should return either a value or a bool status. We could create a struct that carries both value and status:
struct factor_t {
bool is_prime;
long factor;
};
factor_t factor(long n) {
factor_t r{};
for(long i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
r.is_prime = false;
r.factor = i;
return...