Tutorial by Examples

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 std::optional class. For example, an object of type std::optional<int> may contain some value of type int, or it may contain no value. Optionals ar...
Before C++17, having pointers with a value of nullptr commonly represented the absence of a value. This is a good solution for large objects that have been dynamically allocated and are already managed by pointers. However, this solution does not work well for small or primitive types such as int, w...
Before C++17, a function typically represented failure in one of several ways: A null pointer was returned. e.g. Calling a function Delegate *App::get_delegate() on an App instance that did not have a delegate would return nullptr. This is a good solution for objects that have been dynamicall...
std::optional<float> divide(float a, float b) { if (b!=0.f) return a/b; return {}; } Here we return either the fraction a/b, but if it is not defined (would be infinity) we instead return the empty optional. A more complex case: template<class Range, class Pred> auto find_if...
void print_name( std::ostream& os, std::optional<std::string> const& name ) { std::cout "Name is: " << name.value_or("<name missing>") << '\n'; } value_or either returns the value stored in the optional, or the argument if there is nothing s...

Page 1 of 1