C++workingcpp17

optional and variant

Model a maybe-value with std::optional and a fixed set of alternatives with std::variant — no sentinels, no unions, no out-params.

std::optional<T> says "a T or nothing" and std::variant<A, B> says "exactly one of these types"; together they cover the two cases a raw pointer or tagged union used to fumble.

optional return + value_or

C++intro
0ms
a=8080b=80
Reference · output compiled offline, not runnable in-browser

a=8080 shows value_or returning the engaged optional's parsed value, while b=80 shows it falling back because parsePort("") returned std::nullopt — one call replaces the whole "is it there? else default" branch.