Standard Library
Optional Values
std::optional represents a value that may or may not be present.
Optional Values
optional_values.cpp
#include <iostream>
#include <optional>
#include <string>
std::optional<int> readCount(const std::string& text) {
if (text == "none") {
return std::nullopt;
}
return std::stoi(text);
}
int main() {
std::string raw = ;
std::optional<int> count = readCount(raw);
if (count.has_value()) {
std::cout << "count=" << count.value() << std::endl;
} else {
std::cout << "count=missing" << std::endl;
}
std::cout << "fallback=" << count.value_or(0) << std::endl;
return 0;
}
#include <iostream>
#include <optional>
#include <string>
std::optional<int> readCount(const std::string& text) {
if (text == "none") {
return std::nullopt;
}
return std::stoi(text);
}
int main() {
std::string raw = ;
std::optional<int> count = readCount(raw);
if (count.has_value()) {
std::cout << "count=" << count.value() << std::endl;
} else {
std::cout << "count=missing" << std::endl;
}
std::cout << "fallback=" << count.value_or(0) << std::endl;
return 0;
}
#include <iostream>
#include <optional>
#include <string>
std::optional<int> readCount(const std::string& text) {
if (text == "none") {
return std::nullopt;
}
return std::stoi(text);
}
int main() {
std::string raw = ;
std::optional<int> count = readCount(raw);
if (count.has_value()) {
std::cout << "count=" << count.value() << std::endl;
} else {
std::cout << "count=missing" << std::endl;
}
std::cout << "fallback=" << count.value_or(0) << std::endl;
return 0;
}
optional
An optional value makes the missing-value case visible instead of using a special number.