Advanced level · Module 3: Modern C++17 and C++20 Features · Lesson 2 of 4
optional and variant
Represent 'maybe a value' with std::optional and 'one of several types' with std::variant instead of special values.
In this lesson you will
- Return std::optional instead of sentinel values
- Model alternatives with std::variant and handle them with std::visit
Key concepts
std::optionalvalue_orstd::variantstd::visit
The lesson
Functions often signal 'not found' with special values such as -1 or an empty string, which callers forget to check. std::optional<T> makes absence explicit: std::optional<double> parseReading(std::string_view text). Callers test it with if (r) or use r.value_or(0.0).
std::variant<A, B, C> holds exactly one of several types at a time, for example std::variant<Reading, ParseError>. std::visit calls a function with whichever type is held, and the compiler checks that every alternative is handled.
These types make the possible results part of the function's signature, so the compiler helps callers handle every case.
Step by step
- Change a function returning -1 for failure to return std::optional.
- Update the callers to check the result.
- Return std::variant<Reading, ParseError> from the parser.
- Handle both cases with std::visit and an overloaded lambda set.
Practice activity
Complete the parser rewrite from the practical activity using std::optional or std::variant.
Expected result: No special values remain, and every caller handles both success and failure explicitly.
Check your understanding
-
What is the advantage of std::optional over returning -1?
Show answer
Absence is explicit in the type, so callers must handle it.
-
What does std::visit do?
Show answer
Calls a function with the alternative currently held by a variant.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.