value_or

suggest change
void print_name( std::ostream& os, std::optional<std::string> const& name ) {
  os << "Name is: " << name.value_or("<name missing>") << '\n';
}

std::optional::value_or (C++17) returns a copy of the stored value, or a value constructed from the argument if nothing is stored there.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents