typestar

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

  1. parse_port returns std::optional<int> — a value on success, std::nullopt otherwise.
  2. find_first_not_of rejects any text holding a non-digit before std::stoi ever runs.
  3. value_or(8080) unwraps the result or falls back to the default in one call.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Modern touches, step 22 of 27 in Language basics.

← Previous Next →