C++ - Optional, Variant, Any, Tuple

Overview

Estimated time: 60–80 minutes

Use modern utility types for expressive APIs: optional for maybe-values, variant for tagged unions, any for type erasure, and tuple for multiple returns.

Learning Objectives

  • Return optional values instead of sentinel values.
  • Model sum types with variant and visit patterns.
  • Use tuple for multi-return and structured bindings.

Prerequisites

optional

#include 
#include 
std::optional find_even(int x){ return x%2==0 ? std::optional{x} : std::nullopt; }
int main(){ if (auto v = find_even(4)) std::cout << *v << "\n"; }

variant with visit

#include 
#include 
int main(){
  std::variant v = 42;
  std::visit([](auto&& x){ std::cout << x << "\n"; }, v);
  v = std::string("hi");
  std::visit([](auto&& x){ std::cout << x << "\n"; }, v);
}

any and tuple

#include 
#include 
#include 
int main(){
  std::any a = 3.14;
  std::cout << std::any_cast(a) << "\n";
  auto t = std::make_tuple(1, std::string("x"));
  auto [i,s] = t; std::cout << i << ":" << s << "\n";
}

Common Pitfalls

  • any_cast throws on bad type; prefer std::optional or check type alternative (using typeid) when needed.
  • variant index misuse; use std::get_if or visit to avoid bad_variant_access.

Checks for Understanding

  1. When use optional vs variant?
  2. How to access the active variant safely?
Show answers
  1. optional for maybe single type; variant when one of several types.
  2. std::visit or std::get_if.

Exercises

  1. Return optional from a parse_double function and test error handling.
  2. Model a Result variant with Ok or Error; write a printer with visit.