Using std::optional
as a return type is a good choice when a function might not always have a meaningful value to return. Some common scenarios include:
If a function searches for a value in a data structure and the value might not be present, it can return an std::optional
. The presence of a value in the returned optional indicates that the value was found.
#include <optional>
#include <vector>
std::optional<int> find_value(
const std::vector<int>& vec, int value) {
for (int i : vec) {
if (i == value) {
return i;
}
}
return std::nullopt;
}
If a function tries to parse a value from input and the input might be invalid, it can return an std::optional
. The presence of a value in the returned optional indicates that the parsing was successful.
#include <optional>
#include <string>
std::optional<int> parse_int(
const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return std::nullopt;
}
}
If a function computes a result and the computation might fail or not be possible for certain inputs, it can return an std::optional
. The presence of a value in the returned optional indicates that the computation succeeded.
#include <cmath>
#include <optional>
std::optional<double> sqrt_positive(double x) {
if (x >= 0) {
return sqrt(x);
} else {
return std::nullopt;
}
}
In all these cases, using std::optional
makes it clear to the caller that the function might not always return a value, and provides a clean way to handle that situation.
Answers to questions are automatically generated and may not have been reviewed.
std::optional
A comprehensive guide to using std::optional
to represent values that may or may not be present.