Represents a value that may or may not be present — a type-safe replacement for sentinel values like -1 or nullptr.
Include: #include <optional> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::optional<T> | class template | Holds an optional value of type T |
| std::nullopt | constant | Represents an empty optional |
| std::make_optional(x) | optional<T> | Create an optional containing x |
| opt.has_value() | bool | True if optional contains a value |
| (bool)opt | bool | Same as has_value() |
| opt.value() | T & | Return value; throws if empty |
| opt.value_or(def) | T | Return value or def if empty |
| *opt | T & | Dereference (UB if empty — check first) |
| opt.reset() | void | Destroy the contained value |
| opt.emplace(…) | T & | Construct value in-place |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <optional>
#include <string>
#include <vector>
using namespace std;
optional<int> find_index(const vector<string> &v, const string &target) {
for (size_t i = 0; i < v.size(); i++)
if (v[i] == target) return (int)i;
return nullopt;
}
optional<double> safe_sqrt(double x) {
if (x < 0) return nullopt;
return sqrt(x);
}
int main() {
vector<string> fruits = {"apple", "banana", "cherry"};
if (auto idx = find_index(fruits, "banana"))
cout << "banana at index " << *idx << "\n";
else
cout << "banana not found\n";
if (auto idx = find_index(fruits, "durian"))
cout << "durian at index " << *idx << "\n";
else
cout << "durian not found\n";
cout << "sqrt(-4) = " << safe_sqrt(-4.0).value_or(-1.0) << "\n";
cout << "sqrt(9) = " << safe_sqrt(9.0).value() << "\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o optional_demo optional_demo.cpp