optional and value_or in C++
Maybe-a-value without sentinel numbers: std::optional turns bad input into a clean no.
#include <optional>
#include <string>
std::optional<int> parse_port(const std::string &text) {
if (text.empty() ||
text.find_first_not_of("0123456789") != text.npos) {
return std::nullopt;
}
return std::stoi(text);
}
int port_or_default(const std::string &text) {
return parse_port(text).value_or(8080);
}
How it works
parse_portreturnsstd::optional<int>— a value on success,std::nulloptotherwise.find_first_not_ofrejects any text holding a non-digit beforestd::stoiever runs.value_or(8080)unwraps the result or falls back to the default in one call.
Keywords and builtins used here
constifintreturn
The run, in numbers
- Lines
- 14
- Characters to type
- 307
- Tokens
- 89
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 76 seconds.
Step 1 of 3 in Modern touches, step 22 of 27 in Language basics.