Programming paths / C++ Tutorial / std::optional and std::variant for Explicit States

C++ course contents

Beginner

  1. What Modern C++ Is Good For
  2. Set Up a Compiler and Build a C++ Program
  3. Write Your First C++ Program
  4. Types, Initialization, and auto
  5. const, constexpr, and Compile-Time Values
  6. Console Input and Validation
  7. Operators, Conversions, and Integer Arithmetic
  8. Branching with if, switch, and Scoped Variables
  9. Loops and Range-Based for
  10. Functions, Parameters, and Return Values
  11. Built-In Arrays, std::array, and std::vector
  12. std::string, std::string_view, and Text Boundaries
  13. Structures, enum class, and Aggregate Initialization
  14. References, Pointers, and nullptr

Intermediate

  1. Classes, Encapsulation, and Invariants
  2. Constructors, Destructors, and Object Lifetimes
  3. RAII and Deterministic Resource Management
  4. Copying, Moving, and Value Semantics
  5. Smart Pointers and Ownership Choices
  6. STL Containers and Their Trade-Offs
  7. Iterators and Standard Algorithms
  8. Lambdas, Captures, and Callable Objects
  9. Function Templates and Type Deduction
  10. Exceptions and Exception-Safe Design
  11. std::optional and std::variant for Explicit States
  12. Files, Streams, and the Filesystem Library
  13. Headers, Translation Units, and the One Definition Rule

Advanced

  1. Concepts and Constrained Templates
  2. Ranges and Views in C++20
  3. Value Categories, std::move, and Perfect Forwarding
  4. Operator Overloading and Regular Types
  5. constexpr, consteval, and Compile-Time Programming
  6. Threads, Tasks, and Shared State
  7. Data Races, Atomics, and Memory Ordering
  8. Choosing Between Exceptions, optional, and Expected Results
  9. Undefined Behavior, Object Lifetimes, and Valid Programs
  10. Project Builds with CMake
  11. C++ Modules: Interfaces and Toolchain Support
  12. Unit Testing, Assertions, and Testable Design
  13. Profiling, Complexity, and Performance
  14. Secure C++: Input, Bounds, and Resource Ownership

Expert

  1. Designing C++ APIs and Library Boundaries
  2. Linkers, Libraries, and ABI Compatibility
  3. C++23 Features and std::expected
  4. Capstone: Build a Tested Command-Line Catalog

Modern C++ • C++20 baseline

std::optional and std::variant for Explicit States

Represent absence or one-of-many alternatives in types instead of using magic values.

std::optional<T> represents either a T or no value. std::variant<Ts...> represents one active alternative from a closed set. These types make state visible to callers, but access still requires checking or visitation; do not call value() without a reason to know it is engaged.

Key points

  • optional is useful when “no result” is a normal outcome.
  • variant is useful for a finite set of distinct result forms.

Example

#include <iostream>
#include <optional>
#include <string>

std::optional<int> find_code(const std::string& name) {
    if (name == "ready") {
        return 200;
    }
    return std::nullopt;
}

int main() {
    if (const auto code = find_code("ready")) {
        std::cout << *code << '\n';
    }
}

What to expect

200

Practice exercise

Return std::nullopt for a missing lookup and add a caller branch that handles absence.

Key idea: Make ordinary alternatives explicit in the return type.