std::optional and std::variant
C++17 value wrappers
Interview Relevant: Modern C++ types
Optional and Variant
C++17 types for optional values and type-safe unions.
Code Examples
Optional and variant for safer code.
cpp
1#include <optional>
2#include <variant>
3
4// optional - may or may not have a value
5optional<int> findIndex(vector<int>& v, int target) {
6 for (int i = 0; i < v.size(); i++) {
7 if (v[i] == target) return i;
8 }
9 return nullopt; // No value
10}
11
12auto result = findIndex(v, 5);
13if (result.has_value()) {
14 cout << result.value();
15}
16if (result) {
17 cout << *result; // Dereference
18}
19int val = result.value_or(-1); // Default
20
21// variant - type-safe union
22variant<int, double, string> var;
23var = 42;
24var = 3.14;
25var = "hello";
26
27// Access
28if (holds_alternative<string>(var)) {
29 cout << get<string>(var);
30}
31
32// Visit pattern
33visit([](auto&& arg) {
34 cout << arg << endl;
35}, var);
36
37// any - any type (type-erased)
38#include <any>
39any a = 42;
40a = string("hello");
41string s = any_cast<string>(a);