| Start |
|---|
| Using optionals to represent the absence of a value Before C++17, having pointers with a value of In this example, |
optional as return value Here we return either the fraction A more complex case:
It returns either an empty optional if it was not found, or an optional containing an iterator tothe element if it was. This allows you to do: or even without having to mess around with begin/end iterators and tests. |
| Introduction Optionals (also known as Maybe types) are used to represent a type whose contents may or may not be present. They are implemented in C++17 as the Optionals are commonly used either to represent a value that may not exist or as a return type from a function that can fail to return a meaningful result. Other approaches to optionalThere are many other approach to solving the problem that Optional vs PointerIn some cases, we can provide a pointer to an existing object or Optional vs SentinelA common idiom is to use a special value to indicate that the value is meaningless. This may be 0 or -1 for integral types, or Optional vs |
value_or
This lets you take the maybe-null optional and give a default behavior when you actually need a value. By doing it this way, the "default behavior" decision can be pushed back to the point where it is best made and immediately needed, instead of generating some default value deep in the guts of some engine. |
| Using optionals to represent the failure of a function Before C++17, a function typically represented failure in one of several ways:
In this example, John is given two pets, Fluffy and Furball. The function |
Read Article
https://develop.horje.com/learn/1434/reference