skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-optional
This page is read only. You can view the source, but not change it.
# <optional> **[<optional>](https://en.cppreference.com/w/cpp/header/optional)** represents a value that may or may not be present, a type-safe alternative to returning a null pointer or sentinel value. Use `.has_value()` or the conversion operator to check, and `.value()` or `*` to access the contained value. It's useful for functions that may fail to produce a value but don't need to throw or use exceptions. This example uses optional to return either a found integer or nothing, with type-safe checking and extraction. ```cpp // compile: g++ -std=c++17 -o optionalexample optionalexample.cpp // run: ./optionalexample // description: optional value handling #include <optional> #include <iostream> #include <string> std::optional<int> find_value(const std::string& key) { if (key == "answer") { return 42; } return std::nullopt; } int main() { auto result = find_value("answer"); if (result.has_value()) { std::cout << "found: " << result.value() << "\n"; } auto missing = find_value("unknown"); if (!missing) { std::cout << "not found\n"; } return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top