std::optional
std::optional
is a C++17 standard library utility that represents an object that may or may not contain a value. It is a type-safe alternative to using special values (like nullptr or -1) to indicate “no result.”
#include <iostream>
#include <optional>
#include <string>
std::optional<std::string> find_user(int id) {
if (id == 1) {
return "Alice";
} else {
return std::nullopt; // no value
}
}
int main() {
std::optional<std::string> user = find_user(1);
if (user) { // check if has value
std::cout << "User: " << *user << std::endl;
std::cout << "User: " << user.value() << std::endl;
} else {
std::cout << "User not found\n";
}
std::optional<int> x; // empty
std::cout << x.value_or(42); // prints 42
}