std::optional (C++)

Matthew brought this up when I was telling him about expected (C++).

What is the difference?

  • std::optional represents the presence or absence of a value. It is used in situations where a function might return either a valid value or no value at all, but not an error.
    • It doesn’t provide any mechanism to describe why a value is missing (e.g., no error information).
  • expected represents either a valid value or an error (typically with an associated type, like an error code or error message).

Example

#include <optional>
...
 
std::optional<std::string> findItem(const std::string& item) {
    if (item == "apple" || item == "banana" || item == "orange") {
        return item;
    } 
    return std::nullopt; // No valid value, return std::nullopt
}
 
...
std::optional<std::string> result = findItem("apple");
 
if (result.has_value()) {
    std::cout << "Found item: " << result.value() << std::endl;
} else {
    std::cout << "Item not found!" << std::endl;
}

Note the following (you can’t directly assign the optional value), you need to unwrap the value

std::string s = findItem("apple");  // This will not compile