Tuesday, July 7, 2020

std::optional<> is Useful

Consider this: How many times have you written code where a specific value for a type represents an implicit "empty" value? For example, a string value where an empty string was implicitly "no value"? A number where zero was the "default", "no value" case?

How many times has that bitten you later, where you needed to add secondary variables to indicate if the first value was valid or not? Alternatively, how many data structures have values which may or may not be populated by a caller, and the callee needs to rely on additional or implicit information to discern if the values are valid or not?

Enter std::optional<> (or previously boost::optional<>). This type can be used to express the "null" state for any type, without using secondary variables, implicit value meanings, or other mechanisms (eg: using pointers which might be null).

Usage is easy:
std::optional<std::string> osValue;
osValue.has_value(); // yields false
osValue.value_or( "something" ); // yields "something"
osValue = "else";
osValue.has_value(); // yields true
osValue.value_or( "something" ); // yields "else"

Here's the official reference, for reference: https://en.cppreference.com/w/cpp/utility/optional

Next time you think of a case where something might have a value or "nothing", considering using std::optional<>.


No comments: