C++ std::optional::value_or
std::optional represents either a value or its absence. value_or returns the stored value when present and otherwise returns the supplied fallback.
A simple example
std::optional::value_or
- Start with No integer stored
- Do this Read with the fallback 7
- Result 7
Syntax
reading.value_or(fallback)
Run this example in C++
Save the program as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
Supply a default for a missing measurement
A dataset includes a missing or optional measurement alongside actual numerical values. Make the missing-value policy explicit so a valid zero is not discarded or silently replaced.
#include <iostream>
#include <optional>
#include <array>
int main() {
std::array<std::optional<int>, 2> readings{0, std::nullopt};
for (const auto &reading : readings) std::cout << reading.value_or(-1) << '\n';
return 0;
}
0 -1
A present zero remains zero. Checking presence separately from the numeric value preserves the distinction between an empty sensor slot and a measured zero.
C++ working draft for std::optional::value_or
Look up a borrowed tripod
The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?
Read a room preference
The timetable stores a room choice for the choir club. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?