Step 4 of 6
A Result type
Sometimes the caller needs to know why it failed. A small Result type carries either a value or an error message. (C++23 standardizes this idea as std::expected<T, E>.)
struct Result {
std::optional<int> value;
std::string error;
bool ok() const { return value.has_value(); }
};
Your turn: write Result parse_money(const std::string& s) for amounts like "$2700":
- no leading
$gives error"missing quot; - nothing after the
$, or a non-digit character, gives"not a number" - more than 16000 gives
"over the cap" - otherwise the value